* isearch.el (isearch-wrap-function)
(isearch-push-state-function): New defvars.
(isearch-pop-fun-state): New defsubst.
(isearch-top-state): Call function saved in `isearch-pop-fun-state'.
(isearch-push-state): Set the result of calling
`isearch-push-state-function' to the `isearch-pop-fun-state' field.
(isearch-cancel): Call function saved in `isearch-pop-fun-state' to
restore the mode-specific starting point of terminated search.
(isearch-abort): Call `isearch-cancel' instead of its duplicated code.
(isearch-repeat): Call `isearch-wrap-function' if defined.
(isearch-message-prefix): Don't add prefix "over" to the message
for wrapped search if `isearch-wrap-function' is defined.
(isearch-search): Call function saved in `isearch-pop-fun-state' to
restore the mode-specific starting point of failed search.
@c -*-texinfo-*-@c This is part of the GNU Emacs Lisp Reference Manual.@c Copyright (C) 1990, 1991, 1992, 1993, 1994, 1995, 1998, 1999, 2003@c Free Software Foundation, Inc.@c See the file elisp.texi for copying conditions.@setfilename ../info/modes@node Modes, Documentation, Keymaps, Top@chapter Major and Minor Modes@cindex mode A @dfn{mode} is a set of definitions that customize Emacs and can beturned on and off while you edit. There are two varieties of modes:@dfn{major modes}, which are mutually exclusive and used for editingparticular kinds of text, and @dfn{minor modes}, which provide featuresthat users can enable individually. This chapter describes how to write both major and minor modes, how toindicate them in the mode line, and how they run hooks supplied by theuser. For related topics such as keymaps and syntax tables, see@ref{Keymaps}, and @ref{Syntax Tables}.@menu* Major Modes:: Defining major modes.* Minor Modes:: Defining minor modes.* Mode Line Format:: Customizing the text that appears in the mode line.* Imenu:: How a mode can provide a menu of definitions in the buffer.* Font Lock Mode:: How modes can highlight text according to syntax.* Desktop Save Mode:: How modes can have buffer state saved between Emacs sessions.* Hooks:: How to use hooks; how to write code that provides hooks.@end menu@node Major Modes@section Major Modes@cindex major mode@cindex Fundamental mode Major modes specialize Emacs for editing particular kinds of text.Each buffer has only one major mode at a time. For each major modethere is a function to switch to that mode in the current buffer; itsname should end in @samp{-mode}. These functions work by settingbuffer-local variable bindings and other data associated with thebuffer, such as a local keymap. The effect lasts until you switchto another major mode in the same buffer. The least specialized major mode is called @dfn{Fundamental mode}.This mode has no mode-specific definitions or variable settings, so eachEmacs command behaves in its default manner, and each option is in itsdefault state. All other major modes redefine various keys and options.For example, Lisp Interaction mode provides special key bindings for@kbd{C-j} (@code{eval-print-last-sexp}), @key{TAB}(@code{lisp-indent-line}), and other keys. When you need to write several editing commands to help you perform aspecialized editing task, creating a new major mode is usually a goodidea. In practice, writing a major mode is easy (in contrast towriting a minor mode, which is often difficult). If the new mode is similar to an old one, it is often unwise to modifythe old one to serve two purposes, since it may become harder to use andmaintain. Instead, copy and rename an existing major mode definitionand alter the copy---or define a @dfn{derived mode} (@pxref{DerivedModes}). For example, Rmail Edit mode, which is in@file{emacs/lisp/mail/rmailedit.el}, is a major mode that is very similar toText mode except that it provides two additional commands. Itsdefinition is distinct from that of Text mode, but uses that of Text mode. Even if the new mode is not an obvious derivative of any other mode,it is convenient to use @code{define-derived-mode} with a @code{nil}parent argument, since it automatically enforces the most importantcoding conventions for you.@findex define-generic-mode For a very simple programming language major mode that handlescomments and fontification, you can use @code{define-generic-mode}in @file{generic.el}. Rmail Edit mode offers an example of changing the major modetemporarily for a buffer, so it can be edited in a different way (withordinary Emacs commands rather than Rmail commands). In such cases, thetemporary major mode usually provides a command to switch back to thebuffer's usual mode (Rmail mode, in this case). You might be tempted topresent the temporary redefinitions inside a recursive edit and restorethe usual ones when the user exits; but this is a bad idea because itconstrains the user's options when it is done in more than one buffer:recursive edits must be exited most-recently-entered first. Using analternative major mode avoids this limitation. @xref{RecursiveEditing}. The standard GNU Emacs Lisp library directory tree contains the codefor several major modes, in files such as @file{text-mode.el},@file{texinfo.el}, @file{lisp-mode.el}, @file{c-mode.el}, and@file{rmail.el}. They are found in various subdirectories of the@file{lisp} directory. You can study these libraries to see how modesare written. Text mode is perhaps the simplest major mode aside fromFundamental mode. Rmail mode is a complicated and specialized mode.@menu* Major Mode Conventions:: Coding conventions for keymaps, etc.* Example Major Modes:: Text mode and Lisp modes.* Auto Major Mode:: How Emacs chooses the major mode automatically.* Mode Help:: Finding out how to use a mode.* Derived Modes:: Defining a new major mode based on another major mode.@end menu@node Major Mode Conventions@subsection Major Mode Conventions The code for existing major modes follows various coding conventions,including conventions for local keymap and syntax table initialization,global names, and hooks. Please follow these conventions when youdefine a new major mode. This list of conventions is only partial, because each major modeshould aim for consistency in general with other Emacs major modes.This makes Emacs as a whole more coherent. It is impossible to listhere all the possible points where this issue might come up; if theEmacs developers point out an area where your major mode deviates fromthe usual conventions, please make it compatible.@itemize @bullet@itemDefine a command whose name ends in @samp{-mode}, with no arguments,that switches to the new mode in the current buffer. This commandshould set up the keymap, syntax table, and buffer-local variables in anexisting buffer, without changing the buffer's contents.@itemWrite a documentation string for this command that describes thespecial commands available in this mode. @kbd{C-h m}(@code{describe-mode}) in your mode will display this string.The documentation string may include the special documentationsubstrings, @samp{\[@var{command}]}, @samp{\@{@var{keymap}@}}, and@samp{\<@var{keymap}>}, which enable the documentation to adaptautomatically to the user's own key bindings. @xref{Keys inDocumentation}.@itemThe major mode command should start by calling@code{kill-all-local-variables}. This is what gets rid of thebuffer-local variables of the major mode previously in effect.@itemThe major mode command should set the variable @code{major-mode} to themajor mode command symbol. This is how @code{describe-mode} discoverswhich documentation to print.@itemThe major mode command should set the variable @code{mode-name} to the``pretty'' name of the mode, as a string. This string appears in themode line.@item@cindex functions in modesSince all global names are in the same name space, all the globalvariables, constants, and functions that are part of the mode shouldhave names that start with the major mode name (or with an abbreviationof it if the name is long). @xref{Coding Conventions}.@itemIn a major mode for editing some kind of structured text, such as aprogramming language, indentation of text according to structure isprobably useful. So the mode should set @code{indent-line-function}to a suitable function, and probably customize other variablesfor indentation.@item@cindex keymaps in modesThe major mode should usually have its own keymap, which is used as thelocal keymap in all buffers in that mode. The major mode command shouldcall @code{use-local-map} to install this local map. @xref{ActiveKeymaps}, for more information.This keymap should be stored permanently in a global variable named@code{@var{modename}-mode-map}. Normally the library that defines themode sets this variable.@xref{Tips for Defining}, for advice about how to write the code to setup the mode's keymap variable.@itemThe key sequences bound in a major mode keymap should usually start with@kbd{C-c}, followed by a control character, a digit, or @kbd{@{},@kbd{@}}, @kbd{<}, @kbd{>}, @kbd{:} or @kbd{;}. The other punctuationcharacters are reserved for minor modes, and ordinary letters arereserved for users.A major mode can also rebind the keys @kbd{M-n}, @kbd{M-p} and@kbd{M-s}. The bindings for @kbd{M-n} and @kbd{M-p} should normallybe some kind of ``moving forward and backward,'' but this does notnecessarily mean cursor motion.It is legitimate for a major mode to rebind a standard key sequence ifit provides a command that does ``the same job'' in a way bettersuited to the text this mode is used for. For example, a major modefor editing a programming language might redefine @kbd{C-M-a} to``move to the beginning of a function'' in a way that works better forthat language.It is also legitimate for a major mode to rebind a standard keysequence whose standard meaning is rarely useful in that mode. Forinstance, minibuffer modes rebind @kbd{M-r}, whose standard meaning israrely of any use in the minibuffer. Major modes such as Dired orRmail that do not allow self-insertion of text can reasonably redefineletters and other printing characters as special commands.@itemMajor modes must not define @key{RET} to do anything other than inserta newline. The command to insert a newline and then indent is@kbd{C-j}. Please keep this distinction uniform for all major modes.@itemMajor modes should not alter options that are primarily a matter of userpreference, such as whether Auto-Fill mode is enabled. Leave this toeach user to decide. However, a major mode should customize othervariables so that Auto-Fill mode will work usefully @emph{if} the userdecides to use it.@item@cindex syntax tables in modesThe mode may have its own syntax table or may share one with otherrelated modes. If it has its own syntax table, it should store this ina variable named @code{@var{modename}-mode-syntax-table}. @xref{SyntaxTables}.@itemIf the mode handles a language that has a syntax for comments, it shouldset the variables that define the comment syntax. @xref{Options forComments,, Options Controlling Comments, emacs, The GNU Emacs Manual}.@item@cindex abbrev tables in modesThe mode may have its own abbrev table or may share one with otherrelated modes. If it has its own abbrev table, it should store this ina variable named @code{@var{modename}-mode-abbrev-table}. @xref{AbbrevTables}.@itemThe mode should specify how to do highlighting for Font Lock mode, bysetting up a buffer-local value for the variable@code{font-lock-defaults} (@pxref{Font Lock Mode}).@itemThe mode should specify how Imenu should find the definitions orsections of a buffer, by setting up a buffer-local value for thevariable @code{imenu-generic-expression}, for the pair of variables@code{imenu-prev-index-position-function} and@code{imenu-extract-index-name-function}, or for the variable@code{imenu-create-index-function} (@pxref{Imenu}).@itemUse @code{defvar} or @code{defcustom} to set mode-related variables, sothat they are not reinitialized if they already have a value. (Suchreinitialization could discard customizations made by the user.)@item@cindex buffer-local variables in modesTo make a buffer-local binding for an Emacs customization variable, use@code{make-local-variable} in the major mode command, not@code{make-variable-buffer-local}. The latter function would make thevariable local to every buffer in which it is subsequently set, whichwould affect buffers that do not use this mode. It is undesirable for amode to have such global effects. @xref{Buffer-Local Variables}.With rare exceptions, the only reasonable way to use@code{make-variable-buffer-local} in a Lisp package is for a variablewhich is used only within that package. Using it on a variable used byother packages would interfere with them.@item@cindex mode hook@cindex major mode hookEach major mode should have a @dfn{mode hook} named@code{@var{modename}-mode-hook}. The major mode command should run thathook, with @code{run-mode-hooks}, as the very last thing itdoes. @xref{Hooks}.@itemThe major mode command may start by calling some other major modecommand (called the @dfn{parent mode}) and then alter some of itssettings. A mode that does this is called a @dfn{derived mode}. Therecommended way to define one is to use @code{define-derived-mode},but this is not required. Such a mode should use@code{delay-mode-hooks} around its entire body, including the call tothe parent mode command and the final call to @code{run-mode-hooks}.(Using @code{define-derived-mode} does this automatically.)@itemIf something special should be done if the user switches a buffer fromthis mode to any other major mode, this mode can set up a buffer-localvalue for @code{change-major-mode-hook} (@pxref{Creating Buffer-Local}).@itemIf this mode is appropriate only for specially-prepared text, then themajor mode command symbol should have a property named @code{mode-class}with value @code{special}, put on as follows:@kindex mode-class @r{(property)}@cindex @code{special}@example(put 'funny-mode 'mode-class 'special)@end example@noindentThis tells Emacs that new buffers created while the current buffer is inFunny mode should not inherit Funny mode. Modes such as Dired, Rmail,and Buffer List use this feature.@itemIf you want to make the new mode the default for files with certainrecognizable names, add an element to @code{auto-mode-alist} to selectthe mode for those file names. If you define the mode command toautoload, you should add this element in the same file that calls@code{autoload}. Otherwise, it is sufficient to add the element in thefile that contains the mode definition. @xref{Auto Major Mode}.@itemIn the documentation, you should provide a sample @code{autoload} formand an example of how to add to @code{auto-mode-alist}, that users caninclude in their init files (@pxref{Init File}).@item@cindex mode loadingThe top-level forms in the file defining the mode should be written sothat they may be evaluated more than once without adverse consequences.Even if you never load the file more than once, someone else will.@end itemize@node Example Major Modes@subsection Major Mode Examples Text mode is perhaps the simplest mode besides Fundamental mode.Here are excerpts from @file{text-mode.el} that illustrate many ofthe conventions listed above:@smallexample@group;; @r{Create mode-specific tables.}(defvar text-mode-syntax-table nil "Syntax table used while in text mode.")@end group@group(if text-mode-syntax-table () ; @r{Do not change the table if it is already set up.} (setq text-mode-syntax-table (make-syntax-table)) (modify-syntax-entry ?\" ". " text-mode-syntax-table) (modify-syntax-entry ?\\ ". " text-mode-syntax-table) (modify-syntax-entry ?' "w " text-mode-syntax-table))@end group@group(defvar text-mode-abbrev-table nil "Abbrev table used while in text mode.")(define-abbrev-table 'text-mode-abbrev-table ())@end group@group(defvar text-mode-map nil ; @r{Create a mode-specific keymap.} "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.")(if text-mode-map () ; @r{Do not change the keymap if it is already set up.} (setq text-mode-map (make-sparse-keymap)) (define-key text-mode-map "\e\t" 'ispell-complete-word) (define-key text-mode-map "\t" 'indent-relative) (define-key text-mode-map "\es" 'center-line) (define-key text-mode-map "\eS" 'center-paragraph))@end group@end smallexample This was formerly the complete major mode function definition for Text mode:@smallexample@group(defun text-mode () "Major mode for editing text intended for humans to read... Special commands: \\@{text-mode-map@}@end group@groupTurning on text-mode runs the hook `text-mode-hook'." (interactive) (kill-all-local-variables) (use-local-map text-mode-map)@end group@group (setq local-abbrev-table text-mode-abbrev-table) (set-syntax-table text-mode-syntax-table)@end group@group (make-local-variable 'paragraph-start) (setq paragraph-start (concat "[ \t]*$\\|" page-delimiter)) (make-local-variable 'paragraph-separate) (setq paragraph-separate paragraph-start) (make-local-variable 'indent-line-function) (setq indent-line-function 'indent-relative-maybe)@end group@group (setq mode-name "Text") (setq major-mode 'text-mode) (run-mode-hooks 'text-mode-hook)) ; @r{Finally, this permits the user to} ; @r{customize the mode with a hook.}@end group@end smallexample@cindex @file{lisp-mode.el} The three Lisp modes (Lisp mode, Emacs Lisp mode, and LispInteraction mode) have more features than Text mode and the code iscorrespondingly more complicated. Here are excerpts from@file{lisp-mode.el} that illustrate how these modes are written.@cindex syntax table example@smallexample@group;; @r{Create mode-specific table variables.}(defvar lisp-mode-syntax-table nil "")(defvar emacs-lisp-mode-syntax-table nil "")(defvar lisp-mode-abbrev-table nil "")@end group@group(if (not emacs-lisp-mode-syntax-table) ; @r{Do not change the table} ; @r{if it is already set.} (let ((i 0)) (setq emacs-lisp-mode-syntax-table (make-syntax-table))@end group@group ;; @r{Set syntax of chars up to 0 to class of chars that are} ;; @r{part of symbol names but not words.} ;; @r{(The number 0 is @code{48} in the @acronym{ASCII} character set.)} (while (< i ?0) (modify-syntax-entry i "_ " emacs-lisp-mode-syntax-table) (setq i (1+ i))) @dots{}@end group@group ;; @r{Set the syntax for other characters.} (modify-syntax-entry ? " " emacs-lisp-mode-syntax-table) (modify-syntax-entry ?\t " " emacs-lisp-mode-syntax-table) @dots{}@end group@group (modify-syntax-entry ?\( "() " emacs-lisp-mode-syntax-table) (modify-syntax-entry ?\) ")( " emacs-lisp-mode-syntax-table) @dots{}));; @r{Create an abbrev table for lisp-mode.}(define-abbrev-table 'lisp-mode-abbrev-table ())@end group@end smallexample Much code is shared among the three Lisp modes. The followingfunction sets various variables; it is called by each of the major Lispmode functions:@smallexample@group(defun lisp-mode-variables (lisp-syntax) (cond (lisp-syntax (set-syntax-table lisp-mode-syntax-table))) (setq local-abbrev-table lisp-mode-abbrev-table) @dots{}@end group@end smallexample Functions such as @code{forward-paragraph} use the value of the@code{paragraph-start} variable. Since Lisp code is different fromordinary text, the @code{paragraph-start} variable needs to be setspecially to handle Lisp. Also, comments are indented in a specialfashion in Lisp and the Lisp modes need their own mode-specific@code{comment-indent-function}. The code to set these variables is therest of @code{lisp-mode-variables}.@smallexample@group (make-local-variable 'paragraph-start) (setq paragraph-start (concat page-delimiter "\\|$" )) (make-local-variable 'paragraph-separate) (setq paragraph-separate paragraph-start) @dots{}@end group@group (make-local-variable 'comment-indent-function) (setq comment-indent-function 'lisp-comment-indent)) @dots{}@end group@end smallexample Each of the different Lisp modes has a slightly different keymap. Forexample, Lisp mode binds @kbd{C-c C-z} to @code{run-lisp}, but the otherLisp modes do not. However, all Lisp modes have some commands incommon. The following code sets up the common commands:@smallexample@group(defvar shared-lisp-mode-map () "Keymap for commands shared by all sorts of Lisp modes.")(if shared-lisp-mode-map () (setq shared-lisp-mode-map (make-sparse-keymap)) (define-key shared-lisp-mode-map "\e\C-q" 'indent-sexp) (define-key shared-lisp-mode-map "\177" 'backward-delete-char-untabify))@end group@end smallexample@noindentAnd here is the code to set up the keymap for Lisp mode:@smallexample@group(defvar lisp-mode-map () "Keymap for ordinary Lisp mode...")(if lisp-mode-map () (setq lisp-mode-map (make-sparse-keymap)) (set-keymap-parent lisp-mode-map shared-lisp-mode-map) (define-key lisp-mode-map "\e\C-x" 'lisp-eval-defun) (define-key lisp-mode-map "\C-c\C-z" 'run-lisp))@end group@end smallexample Finally, here is the complete major mode function definition forLisp mode.@smallexample@group(defun lisp-mode () "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 jobor to switch back to an existing one.@end group@groupEntry to this mode calls the value of `lisp-mode-hook'if that value is non-nil." (interactive) (kill-all-local-variables)@end group@group (use-local-map lisp-mode-map) ; @r{Select the mode's keymap.} (setq major-mode 'lisp-mode) ; @r{This is how @code{describe-mode}} ; @r{finds out what to describe.} (setq mode-name "Lisp") ; @r{This goes into the mode line.} (lisp-mode-variables t) ; @r{This defines various variables.}@end group@group (setq imenu-case-fold-search t) (set-syntax-table lisp-mode-syntax-table) (run-mode-hooks 'lisp-mode-hook)) ; @r{This permits the user to use a} ; @r{hook to customize the mode.}@end group@end smallexample@node Auto Major Mode@subsection How Emacs Chooses a Major Mode Based on information in the file name or in the file itself, Emacsautomatically selects a major mode for the new buffer when a file isvisited. It also processes local variables specified in the file text.@deffn Command fundamental-mode Fundamental mode is a major mode that is not specialized for anythingin particular. Other major modes are defined in effect by comparisonwith this one---their definitions say what to change, starting fromFundamental mode. The @code{fundamental-mode} function does @emph{not}run any hooks; you're not supposed to customize it. (If you want Emacsto behave differently in Fundamental mode, change the @emph{global}state of Emacs.)@end deffn@deffn Command normal-mode &optional find-fileThis function establishes the proper major mode and buffer-local variablebindings for the current buffer. First it calls @code{set-auto-mode},then it runs @code{hack-local-variables} to parse, and bind orevaluate as appropriate, the file's local variables.If the @var{find-file} argument to @code{normal-mode} is non-@code{nil},@code{normal-mode} assumes that the @code{find-file} function is callingit. In this case, it may process a local variables list at the end ofthe file and in the @samp{-*-} line. The variable@code{enable-local-variables} controls whether to do so. @xref{Filevariables, , Local Variables in Files, emacs, The GNU Emacs Manual}, forthe syntax of the local variables section of a file.If you run @code{normal-mode} interactively, the argument@var{find-file} is normally @code{nil}. In this case,@code{normal-mode} unconditionally processes any local variables list.@cindex file mode specification error@code{normal-mode} uses @code{condition-case} around the call to themajor mode function, so errors are caught and reported as a @samp{Filemode specification error}, followed by the original error message.@end deffn@defun set-auto-mode@cindex visited file mode This function selects the major mode that is appropriate for thecurrent buffer. It may base its decision on the value of the @w{@samp{-*-}}line, on the visited file name (using @code{auto-mode-alist}), on the@w{@samp{#!}} line (using @code{interpreter-mode-alist}), or on thefile's local variables list. However, this function does not look forthe @samp{mode:} local variable near the end of a file; the@code{hack-local-variables} function does that. @xref{Choosing Modes, ,How Major Modes are Chosen, emacs, The GNU Emacs Manual}.@end defun@defopt default-major-modeThis variable holds the default major mode for new buffers. Thestandard value is @code{fundamental-mode}.If the value of @code{default-major-mode} is @code{nil}, Emacs usesthe (previously) current buffer's major mode for the major mode of a newbuffer. However, if that major mode symbol has a @code{mode-class}property with value @code{special}, then it is not used for new buffers;Fundamental mode is used instead. The modes that have this property arethose such as Dired and Rmail that are useful only with text that hasbeen specially prepared.@end defopt@defun set-buffer-major-mode bufferThis function sets the major mode of @var{buffer} to the value of@code{default-major-mode}. If that variable is @code{nil}, it usesthe current buffer's major mode (if that is suitable).The low-level primitives for creating buffers do not use this function,but medium-level commands such as @code{switch-to-buffer} and@code{find-file-noselect} use it whenever they create buffers.@end defun@defvar initial-major-mode@cindex @samp{*scratch*}The value of this variable determines the major mode of the initial@samp{*scratch*} buffer. The value should be a symbol that is a majormode command. The default value is @code{lisp-interaction-mode}.@end defvar@defvar auto-mode-alistThis variable contains an association list of file name patterns(regular expressions; @pxref{Regular Expressions}) and correspondingmajor mode commands. Usually, the file name patterns test for suffixes,such as @samp{.el} and @samp{.c}, but this need not be the case. Anordinary element of the alist looks like @code{(@var{regexp} .@var{mode-function})}.For example,@smallexample@group(("\\`/tmp/fol/" . text-mode) ("\\.texinfo\\'" . texinfo-mode) ("\\.texi\\'" . texinfo-mode)@end group@group ("\\.el\\'" . emacs-lisp-mode) ("\\.c\\'" . c-mode) ("\\.h\\'" . c-mode) @dots{})@end group@end smallexampleWhen you visit a file whose expanded file name (@pxref{File NameExpansion}) matches a @var{regexp}, @code{set-auto-mode} calls thecorresponding @var{mode-function}. This feature enables Emacs to selectthe proper major mode for most files.If an element of @code{auto-mode-alist} has the form @code{(@var{regexp}@var{function} t)}, then after calling @var{function}, Emacs searches@code{auto-mode-alist} again for a match against the portion of the filename that did not match before. This feature is useful foruncompression packages: an entry of the form @code{("\\.gz\\'"@var{function} t)} can uncompress the file and then put the uncompressedfile in the proper mode according to the name sans @samp{.gz}.Here is an example of how to prepend several pattern pairs to@code{auto-mode-alist}. (You might use this sort of expression in yourinit file.)@smallexample@group(setq auto-mode-alist (append ;; @r{File name (within directory) starts with a dot.} '(("/\\.[^/]*\\'" . fundamental-mode) ;; @r{File name has no dot.} ("[^\\./]*\\'" . fundamental-mode) ;; @r{File name ends in @samp{.C}.} ("\\.C\\'" . c++-mode)) auto-mode-alist))@end group@end smallexample@end defvar@defvar interpreter-mode-alistThis variable specifies major modes to use for scripts that specify acommand interpreter in a @samp{#!} line. Its value is a list ofelements of the form @code{(@var{interpreter} . @var{mode})}; forexample, @code{("perl" . perl-mode)} is one element present by default.The element says to use mode @var{mode} if the file specifiesan interpreter which matches @var{interpreter}. The value of@var{interpreter} is actually a regular expression.This variable is applicable only when the @code{auto-mode-alist} doesnot indicate which major mode to use.@end defvar@node Mode Help@subsection Getting Help about a Major Mode@cindex mode help@cindex help for major mode@cindex documentation for major mode The @code{describe-mode} function is used to provide informationabout major modes. It is normally called with @kbd{C-h m}. The@code{describe-mode} function uses the value of @code{major-mode},which is why every major mode function needs to set the@code{major-mode} variable.@deffn Command describe-modeThis function displays the documentation of the current major mode.The @code{describe-mode} function calls the @code{documentation}function using the value of @code{major-mode} as an argument. Thus, itdisplays the documentation string of the major mode function.(@xref{Accessing Documentation}.)@end deffn@defvar major-modeThis variable holds the symbol for the current buffer's major mode.This symbol should have a function definition that is the command toswitch to that major mode. The @code{describe-mode} function uses thedocumentation string of the function as the documentation of the majormode.@end defvar@node Derived Modes@subsection Defining Derived Modes It's often useful to define a new major mode in terms of an existingone. An easy way to do this is to use @code{define-derived-mode}.@defmac define-derived-mode variant parent name docstring body@dots{}This construct defines @var{variant} as a major mode command, using@var{name} as the string form of the mode name.The new command @var{variant} is defined to call the function@var{parent}, then override certain aspects of that parent mode:@itemize @bullet@itemThe new mode has its own keymap, named @code{@var{variant}-map}.@code{define-derived-mode} initializes this map to inherit from@code{@var{parent}-map}, if it is not already set.@itemThe new mode has its own syntax table, kept in the variable@code{@var{variant}-syntax-table}.@code{define-derived-mode} initializes this variable by copying@code{@var{parent}-syntax-table}, if it is not already set.@itemThe new mode has its own abbrev table, kept in the variable@code{@var{variant}-abbrev-table}.@code{define-derived-mode} initializes this variable by copying@code{@var{parent}-abbrev-table}, if it is not already set.@itemThe new mode has its own mode hook, @code{@var{variant}-hook},which it runs in standard fashion as the very last thing that it does.(The new mode also runs the mode hook of @var{parent} as partof calling @var{parent}.)@end itemizeIn addition, you can specify how to override other aspects of@var{parent} with @var{body}. The command @var{variant}evaluates the forms in @var{body} after setting up all its usualoverrides, just before running @code{@var{variant}-hook}.The argument @var{docstring} specifies the documentation string for thenew mode. If you omit @var{docstring}, @code{define-derived-mode}generates a documentation string.Here is a hypothetical example:@example(define-derived-mode hypertext-mode text-mode "Hypertext" "Major mode for hypertext.\\@{hypertext-mode-map@}" (setq case-fold-search nil))(define-key hypertext-mode-map [down-mouse-3] 'do-hyper-link)@end exampleDo not write an @code{interactive} spec in the definition;@code{define-derived-mode} does that automatically.@end defmac@node Minor Modes@section Minor Modes@cindex minor mode A @dfn{minor mode} provides features that users may enable or disableindependently of the choice of major mode. Minor modes can be enabledindividually or in combination. Minor modes would be better named``generally available, optional feature modes,'' except that such a namewould be unwieldy. A minor mode is not usually meant as a variation of a single major mode.Usually they are general and can apply to many major modes. Forexample, Auto Fill mode works with any major mode that permits textinsertion. To be general, a minor mode must be effectively independentof the things major modes do. A minor mode is often much more difficult to implement than a majormode. One reason is that you should be able to activate and deactivateminor modes in any order. A minor mode should be able to have itsdesired effect regardless of the major mode and regardless of the otherminor modes in effect. Often the biggest problem in implementing a minor mode is finding away to insert the necessary hook into the rest of Emacs. Minor modekeymaps make this easier than it used to be.@defvar minor-mode-listThe value of this variable is a list of all minor mode commands.@end defvar@menu* Minor Mode Conventions:: Tips for writing a minor mode.* Keymaps and Minor Modes:: How a minor mode can have its own keymap.* Defining Minor Modes:: A convenient facility for defining minor modes.@end menu@node Minor Mode Conventions@subsection Conventions for Writing Minor Modes@cindex minor mode conventions@cindex conventions for writing minor modes There are conventions for writing minor modes just as there are formajor modes. Several of the major mode conventions apply to minormodes as well: those regarding the name of the mode initializationfunction, the names of global symbols, and the use of keymaps andother tables. In addition, there are several conventions that are specific tominor modes.@itemize @bullet@item@cindex mode variableMake a variable whose name ends in @samp{-mode} to control the minormode. We call this the @dfn{mode variable}. The minor mode commandshould set this variable (@code{nil} to disable; anything else toenable).If possible, implement the mode so that setting the variableautomatically enables or disables the mode. Then the minor mode commanddoes not need to do anything except set the variable.This variable is used in conjunction with the @code{minor-mode-alist} todisplay the minor mode name in the mode line. It can also enableor disable a minor mode keymap. Individual commands or hooks can alsocheck the variable's value.If you want the minor mode to be enabled separately in each buffer,make the variable buffer-local.@itemDefine a command whose name is the same as the mode variable.Its job is to enable and disable the mode by setting the variable.The command should accept one optional argument. If the argument is@code{nil}, it should toggle the mode (turn it on if it is off, andoff if it is on). It should turn the mode on if the argument is apositive integer, the symbol @code{t}, or a list whose @sc{car} is oneof those. It should turn the mode off if the argument is a negativeinteger or zero, the symbol @code{-}, or a list whose @sc{car} is anegative integer or zero. The meaning of other arguments is notspecified.Here is an example taken from the definition of @code{transient-mark-mode}.It shows the use of @code{transient-mark-mode} as a variable that enables ordisables the mode's behavior, and also shows the proper way to toggle,enable or disable the minor mode based on the raw prefix argument value.@smallexample@group(setq transient-mark-mode (if (null arg) (not transient-mark-mode) (> (prefix-numeric-value arg) 0)))@end group@end smallexample@itemAdd an element to @code{minor-mode-alist} for each minor mode(@pxref{Mode Line Variables}), if you want to indicate the minor mode inthe mode line. This element should be a list of the following form:@smallexample(@var{mode-variable} @var{string})@end smallexampleHere @var{mode-variable} is the variable that controls enabling of theminor mode, and @var{string} is a short string, starting with a space,to represent the mode in the mode line. These strings must be short sothat there is room for several of them at once.When you add an element to @code{minor-mode-alist}, use @code{assq} tocheck for an existing element, to avoid duplication. For example:@smallexample@group(unless (assq 'leif-mode minor-mode-alist) (setq minor-mode-alist (cons '(leif-mode " Leif") minor-mode-alist)))@end group@end smallexample@noindentor like this, using @code{add-to-list} (@pxref{Setting Variables}):@smallexample@group(add-to-list 'minor-mode-alist '(leif-mode " Leif"))@end group@end smallexample@end itemize Global minor modes distributed with Emacs should if possible supportenabling and disabling via Custom (@pxref{Customization}). To do this,the first step is to define the mode variable with @code{defcustom}, andspecify @code{:type boolean}. If just setting the variable is not sufficient to enable the mode, youshould also specify a @code{:set} method which enables the mode byinvoke the mode command. Note in the variable's documentation string thatsetting the variable other than via Custom may not take effect. Also mark the definition with an autoload cookie (@pxref{Autoload}),and specify a @code{:require} so that customizing the variable will loadthe library that defines the mode. This will copy suitable definitionsinto @file{loaddefs.el} so that users can use @code{customize-option} toenable the mode. For example:@smallexample@group;;;###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 (lambda (symbol value) (msb-mode (or value 0))) :initialize 'custom-initialize-default :version "20.4" :type 'boolean :group 'msb :require 'msb)@end group@end smallexample@node Keymaps and Minor Modes@subsection Keymaps and Minor Modes Each minor mode can have its own keymap, which is active when the modeis enabled. To set up a keymap for a minor mode, add an element to thealist @code{minor-mode-map-alist}. @xref{Active Keymaps}.@cindex @code{self-insert-command}, minor modes One use of minor mode keymaps is to modify the behavior of certainself-inserting characters so that they do something else as well asself-insert. In general, this is the only way to do that, since thefacilities for customizing @code{self-insert-command} are limited tospecial cases (designed for abbrevs and Auto Fill mode). (Do not trysubstituting your own definition of @code{self-insert-command} for thestandard one. The editor command loop handles this function specially.)The key sequences bound in a minor mode should consist of @kbd{C-c}followed by a punctuation character @emph{other than} @kbd{@{},@kbd{@}}, @kbd{<}, @kbd{>}, @kbd{:}, and @kbd{;}. (Those few punctuationcharacters are reserved for major modes.)@node Defining Minor Modes@subsection Defining Minor Modes The macro @code{define-minor-mode} offers a convenient way ofimplementing a mode in one self-contained definition. It supports onlybuffer-local minor modes, not global ones.@defmac define-minor-mode mode doc [init-value [lighter [keymap keyword-args... body...]]]@tindex define-minor-modeThis macro defines a new minor mode whose name is @var{mode} (asymbol). It defines a command named @var{mode} to toggle the minormode, with @var{doc} as its documentation string. It also defines avariable named @var{mode}, which is set to @code{t} or @code{nil} byenabling or disabling the mode. The variable is initialized to@var{init-value}.The string @var{lighter} says what to display in the mode linewhen the mode is enabled; if it is @code{nil}, the mode is not displayedin the mode line.The optional argument @var{keymap} specifies the keymap for the minor mode.It can be a variable name, whose value is the keymap, or it can be an alistspecifying bindings in this form:@example(@var{key-sequence} . @var{definition})@end exampleThe @var{keyword-args} consist of keywords followed by correspondingvalues. A few keywords have special meanings:@table @code@item :global @var{global}If non-@code{nil} specifies that the minor mode should be global.By default, minor modes are buffer-local.@item :init-value @var{init-value}This is equivalent to specifying @var{init-value} positionally.@item :lighter @var{lighter}This is equivalent to specifying @var{lighter} positionally.@item :keymap @var{keymap}This is equivalent to specifying @var{keymap} positionally.@end tableAny other keyword arguments are passed passed directly to the@code{defcustom} generated for the variable @var{mode}.The command named @var{mode} finishes by executing the @var{body} forms,if any, after it has performed the standard actions such as settingthe variable named @var{mode}.@end defmac@findex easy-mmode-define-minor-mode The name @code{easy-mmode-define-minor-mode} is an aliasfor this macro. Here is an example of using @code{define-minor-mode}:@smallexample(define-minor-mode hungry-mode "Toggle Hungry mode.With no argument, this command toggles the mode.Non-null prefix argument turns on the mode.Null prefix argument turns off the mode.When Hungry mode is enabled, the control delete keygobbles 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-\^?" . hungry-electric-delete) ("\C-\M-\^?" . (lambda () (interactive) (hungry-electric-delete t)))) :group 'hunger)@end smallexample@noindentThis defines a minor mode named ``Hungry mode'', a command named@code{hungry-mode} to toggle it, a variable named @code{hungry-mode}which indicates whether the mode is enabled, and a variable named@code{hungry-mode-map} which holds the keymap that is active when themode is enabled. It initializes the keymap with key bindings for@kbd{C-@key{DEL}} and @kbd{C-M-@key{DEL}}. It puts the variable@code{hungry-mode} into custom group @code{hunger}. There are no@var{body} forms---many minor modes don't need any. Here's an equivalent way to write it:@smallexample(define-minor-mode hungry-mode "Toggle Hungry mode.With no argument, this command toggles the mode.Non-null prefix argument turns on the mode.Null prefix argument turns off the mode.When Hungry mode is enabled, the control delete keygobbles all preceding whitespace except the last.See the command \\[hungry-electric-delete]." ;; The initial value. :initial-value nil ;; The indicator for the mode line. :lighter " Hungry" ;; The minor mode bindings. :keymap '(("\C-\^?" . hungry-electric-delete) ("\C-\M-\^?" . (lambda () (interactive) (hungry-electric-delete t)))) :group 'hunger)@end smallexample@node Mode Line Format@section Mode-Line Format@cindex mode line Each Emacs window (aside from minibuffer windows) typically has a modeline at the bottom, which displays status information about the bufferdisplayed in the window. The mode line contains information about thebuffer, such as its name, associated file, depth of recursive editing,and major and minor modes. A window can also have a @dfn{headerline}, which is much like the mode line but appears at the top of thewindow (starting in Emacs 21). This section describes how to control the contents of the mode lineand header line. We include it in this chapter because much of theinformation displayed in the mode line relates to the enabled major andminor modes. @code{mode-line-format} is a buffer-local variable that holds atemplate used to display the mode line of the current buffer. Allwindows for the same buffer use the same @code{mode-line-format}, sotheir mode lines appear the same---except for scrolling percentages, andline and column numbers, since those depend on point and on how thewindow is scrolled. @code{header-line-format} is used likewise forheader lines. For efficiency, Emacs does not recompute the mode line and headerline of a window in every redisplay. It does so when circumstancesappear to call for it---for instance, if you change the windowconfiguration, switch buffers, narrow or widen the buffer, scroll, orchange the buffer's modification status. If you modify any of thevariables referenced by @code{mode-line-format} (@pxref{Mode LineVariables}), or any other variables and data structures that affecthow text is displayed (@pxref{Display}), you may want to force anupdate of the mode line so as to display the new information ordisplay it in the new way.@c Emacs 19 feature@defun force-mode-line-update &optional allForce redisplay of the current buffer's mode line and header line.The next redisplay will update the mode line and header line based onthe latest values of all relevant variables. With optionalnon-@code{nil} @var{all}, force redisplay of all mode lines and headerlines.This function also forces recomputation of the menu bar menusand the frame title.@end defun The mode line is usually displayed in inverse video; see@code{mode-line-inverse-video} in @ref{Inverse Video}. A window that is just one line tall does not display either a modeline or a header line, even if the variables call for one. A windowthat is two lines tall cannot display both a mode line and a headerline at once; if the variables call for both, only the mode lineactually appears.@menu* Mode Line Data:: The data structure that controls the mode line.* Mode Line Variables:: Variables used in that data structure.* %-Constructs:: Putting information into a mode line.* Properties in Mode:: Using text properties in the mode line.* Header Lines:: Like a mode line, but at the top.* Emulating Mode Line:: Formatting text as the mode line would.@end menu@node Mode Line Data@subsection The Data Structure of the Mode Line@cindex mode-line construct The mode-line contents are controlled by a data structure of lists,strings, symbols, and numbers kept in buffer-local variables. The datastructure is called a @dfn{mode-line construct}, and it is built inrecursive fashion out of simpler mode-line constructs. The same datastructure is used for constructing frame titles (@pxref{Frame Titles})and header lines (@pxref{Header Lines}).@defvar mode-line-formatThe value of this variable is a mode-line construct with overallresponsibility for the mode-line format. The value of this variablecontrols which other variables are used to form the mode-line text, andwhere they appear.If you set this variable to @code{nil} in a buffer, that buffer does nothave a mode line. (This feature was added in Emacs 21.)@end defvar A mode-line construct may be as simple as a fixed string of text, butit usually specifies how to use other variables to construct the text.Many of these variables are themselves defined to have mode-lineconstructs as their values. The default value of @code{mode-line-format} incorporates the valuesof variables such as @code{mode-line-position} and@code{mode-line-modes} (which in turn incorporates the values of thevariables @code{mode-name} and @code{minor-mode-alist}). Because ofthis, very few modes need to alter @code{mode-line-format} itself. Formost purposes, it is sufficient to alter some of the variables that@code{mode-line-format} either directly or indirectly refers to. A mode-line construct may be a list, a symbol, or a string. If thevalue is a list, each element may be a list, a symbol, or a string. The mode line can display various faces, if the strings that controlit have the @code{face} property. @xref{Properties in Mode}. Inaddition, the face @code{mode-line} is used as a default for the wholemode line (@pxref{Standard Faces}).@table @code@cindex percent symbol in mode line@item @var{string}A string as a mode-line construct is displayed verbatim in the mode lineexcept for @dfn{@code{%}-constructs}. Decimal digits after the @samp{%}specify the field width for space filling on the right (i.e., the datais left justified). @xref{%-Constructs}.@item @var{symbol}A symbol as a mode-line construct stands for its value. The value of@var{symbol} is used as a mode-line construct, in place of @var{symbol}.However, the symbols @code{t} and @code{nil} are ignored, as is anysymbol whose value is void.There is one exception: if the value of @var{symbol} is a string, it isdisplayed verbatim: the @code{%}-constructs are not recognized.Unless @var{symbol} is marked as ``risky'' (i.e., it has anon-@code{nil} @code{risky-local-variable} property), all properties inany strings, as well as all @code{:eval} and @code{:propertize} forms inthe value of that symbol will be ignored.@item (@var{string} @var{rest}@dots{}) @r{or} (@var{list} @var{rest}@dots{})A list whose first element is a string or list means to process all theelements recursively and concatenate the results. This is the mostcommon form of mode-line construct.@item (:eval @var{form})A list whose first element is the symbol @code{:eval} says to evaluate@var{form}, and use the result as a string to display.(This feature is new as of Emacs 21.)@item (:propertize @var{elt} @var{props}@dots{})A list whose first element is the symbol @code{:propertize} says toprocess the mode-line construct @var{elt} recursively and add the textproperties specified by @var{props} to the result. The argument@var{props} should consist of zero or more pairs @var{text-property}@var{value}. (This feature is new as of Emacs 21.4.)@c FIXME: This might be Emacs 21.5.@item (@var{symbol} @var{then} @var{else})A list whose first element is a symbol that is not a keyword specifies aconditional. Its meaning depends on the value of @var{symbol}. If thevalue is non-@code{nil}, the second element, @var{then}, is processedrecursively as a mode-line element. But if the value of @var{symbol} is@code{nil}, the third element, @var{else}, is processed recursively.You may omit @var{else}; then the mode-line element displays nothing ifthe value of @var{symbol} is @code{nil}.@item (@var{width} @var{rest}@dots{})A list whose first element is an integer specifies truncation orpadding of the results of @var{rest}. The remaining elements@var{rest} are processed recursively as mode-line constructs andconcatenated together. Then the result is space filled (if@var{width} is positive) or truncated (to @minus{}@var{width} columns,if @var{width} is negative) on the right.For example, the usual way to show what percentage of a buffer is abovethe top of the window is to use a list like this: @code{(-3 "%p")}.@end table If you do alter @code{mode-line-format} itself, the new value shoulduse the same variables that appear in the default value (@pxref{ModeLine Variables}), rather than duplicating their contents or displayingthe information in another fashion. This way, customizations made bythe user or by Lisp programs (such as @code{display-time} and majormodes) via changes to those variables remain effective.@cindex Shell mode @code{mode-line-format} Here is an example of a @code{mode-line-format} that might beuseful for @code{shell-mode}, since it contains the host name and defaultdirectory.@example@group(setq mode-line-format (list "-" 'mode-line-mule-info 'mode-line-modified 'mode-line-frame-identification "%b--"@end group@group ;; @r{Note that this is evaluated while making the list.} ;; @r{It makes a mode-line construct which is just a string.} (getenv "HOST")@end group ":" 'default-directory " " 'global-mode-string " %[(" '(:eval (mode-line-mode-name)) 'mode-line-process 'minor-mode-alist "%n" ")%]--"@group '(which-func-mode ("" which-func-format "--")) '(line-number-mode "L%l--") '(column-number-mode "C%c--") '(-3 "%p") "-%-"))@end group@end example@noindent(The variables @code{line-number-mode}, @code{column-number-mode}and @code{which-func-mode} enable particular minor modes; as usual,these variable names are also the minor mode command names.)@node Mode Line Variables@subsection Variables Used in the Mode Line This section describes variables incorporated by thestandard value of @code{mode-line-format} into the text of the modeline. There is nothing inherently special about these variables; anyother variables could have the same effects on the mode line if@code{mode-line-format} were changed to use them.@defvar mode-line-mule-infoThis variable holds the value of the mode-line construct that displaysinformation about the language environment, buffer coding system, andcurrent input method. @xref{Non-ASCII Characters}.@end defvar@defvar mode-line-modifiedThis variable holds the value of the mode-line construct that displayswhether the current buffer is modified.The default value of @code{mode-line-modified} is @code{("%1*%1+")}.This means that the mode line displays @samp{**} if the buffer ismodified, @samp{--} if the buffer is not modified, @samp{%%} if thebuffer is read only, and @samp{%*} if the buffer is read only andmodified.Changing this variable does not force an update of the mode line.@end defvar@defvar mode-line-frame-identificationThis variable identifies the current frame. The default value is@code{" "} if you are using a window system which can show multipleframes, or @code{"-%F "} on an ordinary terminal which shows only oneframe at a time.@end defvar@defvar mode-line-buffer-identificationThis variable identifies the buffer being displayed in the window. Itsdefault value is @code{("%12b")}, which displays the buffer name, paddedwith spaces to at least 12 columns.@end defvar@defvar mode-line-positionThis variable indicates the position in the buffer. Here is asimplified version of its default value. The actual default valuealso specifies addition of the @code{help-echo} text property.@example@group((-3 "%p") (size-indication-mode (8 " of %I"))@end group@group (line-number-mode ((column-number-mode (10 " (%l,%c)") (6 " L%l"))) ((column-number-mode (5 " C%c")))))@end group@end exampleThis means that @code{mode-line-position} displays at least the bufferpercentage and possibly the buffer size, the line number and the columnnumber.@end defvar@defvar vc-modeThe variable @code{vc-mode}, buffer-local in each buffer, recordswhether the buffer's visited file is maintained with version control,and, if so, which kind. Its value is a string that appears in the modeline, or @code{nil} for no version control.@end defvar@defvar mode-line-modesThis variable displays the buffer's major and minor modes. Here is asimplified version of its default value. The real default value alsospecifies addition of text properties.@example@group("%[(" mode-name mode-line-process minor-mode-alist "%n" ")%]--")@end group@end exampleSo @code{mode-line-modes} normally also displays the recursive editinglevel, information on the process status and whether narrowing is ineffect.@end defvar The following three variables are used in @code{mode-line-modes}:@defvar mode-nameThis buffer-local variable holds the ``pretty'' name of the currentbuffer's major mode. Each major mode should set this variable so that themode name will appear in the mode line.@end defvar@defvar mode-line-processThis buffer-local variable contains the mode-line information on processstatus in modes used for communicating with subprocesses. It isdisplayed immediately following the major mode name, with no interveningspace. For example, its value in the @samp{*shell*} buffer is@code{(":%s")}, which allows the shell to display its status alongwith the major mode as: @samp{(Shell:run)}. Normally this variableis @code{nil}.@end defvar@defvar minor-mode-alistThis variable holds an association list whose elements specify how themode line should indicate that a minor mode is active. Each element ofthe @code{minor-mode-alist} should be a two-element list:@example(@var{minor-mode-variable} @var{mode-line-string})@end exampleMore generally, @var{mode-line-string} can be any mode-line spec. Itappears in the mode line when the value of @var{minor-mode-variable}is non-@code{nil}, and not otherwise. These strings should begin withspaces so that they don't run together. Conventionally, the@var{minor-mode-variable} for a specific mode is set to anon-@code{nil} value when that minor mode is activated.@code{minor-mode-alist} itself is not buffer-local. Each variablementioned in the alist should be buffer-local if its minor mode can beenabled separately in each buffer.@end defvar@defvar global-mode-stringThis variable holds a mode-line spec that, by default, appears in themode line just after the @code{which-func-mode} minor mode if set,else after @code{mode-line-modes}. The command @code{display-time}sets @code{global-mode-string} to refer to the variable@code{display-time-string}, which holds a string containing the timeand load information.The @samp{%M} construct substitutes the value of@code{global-mode-string}, but that is obsolete, since the variable isincluded in the mode line from @code{mode-line-format}.@end defvar The variable @code{default-mode-line-format} is where@code{mode-line-format} usually gets its value:@defvar default-mode-line-formatThis variable holds the default @code{mode-line-format} for buffersthat do not override it. This is the same as @code{(default-value'mode-line-format)}.Here is a simplified version of the default value of@code{default-mode-line-format}. The real default value alsospecifies addition of text properties.@example@group("-" mode-line-mule-info mode-line-modified mode-line-frame-identification mode-line-buffer-identification@end group " " mode-line-position (vc-mode vc-mode) " "@group mode-line-modes (which-func-mode ("" which-func-format "--")) (global-mode-string ("--" global-mode-string)) "-%-")@end group@end example@end defvar@node %-Constructs@subsection @code{%}-Constructs in the Mode Line The following table lists the recognized @code{%}-constructs and whatthey mean. In any construct except @samp{%%}, you can add a decimalinteger after the @samp{%} to specify how many characters to display.@table @code@item %bThe current buffer name, obtained with the @code{buffer-name} function.@xref{Buffer Names}.@item %cThe current column number of point.@item %fThe visited file name, obtained with the @code{buffer-file-name}function. @xref{Buffer File Name}.@item %FThe title (only on a window system) or the name of the selected frame.@xref{Window Frame Parameters}.@item %iThe size of the accessible part of the current buffer; basically@code{(- (point-max) (point-min))}.@item %ILike @samp{%i}, but the size is printed in a more readable way by using@samp{k} for 10^3, @samp{M} for 10^6, @samp{G} for 10^9, etc., toabbreviate.@item %lThe current line number of point, counting within the accessible portionof the buffer.@item %n@samp{Narrow} when narrowing is in effect; nothing otherwise (see@code{narrow-to-region} in @ref{Narrowing}).@item %pThe percentage of the buffer text above the @strong{top} of window, or@samp{Top}, @samp{Bottom} or @samp{All}. Note that the defaultmode-line specification truncates this to three characters.@item %PThe percentage of the buffer text that is above the @strong{bottom} ofthe window (which includes the text visible in the window, as well asthe text above the top), plus @samp{Top} if the top of the buffer isvisible on screen; or @samp{Bottom} or @samp{All}.@item %sThe status of the subprocess belonging to the current buffer, obtained with@code{process-status}. @xref{Process Information}.@item %tWhether the visited file is a text file or a binary file. This is ameaningful distinction only on certain operating systems (@pxref{MS-DOSFile Types}).@item %*@samp{%} if the buffer is read only (see @code{buffer-read-only}); @*@samp{*} if the buffer is modified (see @code{buffer-modified-p}); @*@samp{-} otherwise. @xref{Buffer Modification}.@item %+@samp{*} if the buffer is modified (see @code{buffer-modified-p}); @*@samp{%} if the buffer is read only (see @code{buffer-read-only}); @*@samp{-} otherwise. This differs from @samp{%*} only for a modifiedread-only buffer. @xref{Buffer Modification}.@item %&@samp{*} if the buffer is modified, and @samp{-} otherwise.@item %[An indication of the depth of recursive editing levels (not countingminibuffer levels): one @samp{[} for each editing level.@xref{Recursive Editing}.@item %]One @samp{]} for each recursive editing level (not counting minibufferlevels).@item %-Dashes sufficient to fill the remainder of the mode line.@item %%The character @samp{%}---this is how to include a literal @samp{%} in astring in which @code{%}-constructs are allowed.@end tableThe following two @code{%}-constructs are still supported, but they areobsolete, since you can get the same results with the variables@code{mode-name} and @code{global-mode-string}.@table @code@item %mThe value of @code{mode-name}.@item %MThe value of @code{global-mode-string}. Currently, only@code{display-time} modifies the value of @code{global-mode-string}.@end table@node Properties in Mode@subsection Properties in the Mode Line@cindex text properties in the mode line Starting in Emacs 21, certain text properties are meaningful in themode line. The @code{face} property affects the appearance of text; the@code{help-echo} property associate help strings with the text, and@code{local-map} can make the text mouse-sensitive. There are four ways to specify text properties for text in the modeline:@enumerate@itemPut a string with a text property directly into the mode-line datastructure.@itemPut a text property on a mode-line %-construct such as @samp{%12b}; thenthe expansion of the %-construct will have that same text property.@itemUse a @code{(:propertize @var{elt} @var{props}@dots{})} construct togive @var{elt} a text property specified by @var{props}.@itemUse a list containing @code{:eval @var{form}} in the mode-line datastructure, and make @var{form} evaluate to a string that has a textproperty.@end enumerate You use the @code{local-map} property to specify a keymap. Like anykeymap, it can bind character keys and function keys; but that has noeffect, since it is impossible to move point into the mode line. Thiskeymap can only take real effect for mouse clicks.@node Header Lines@subsection Window Header Lines@cindex header line (of a window)@cindex window header line Starting in Emacs 21, a window can have a @dfn{header line} at thetop, just as it can have a mode line at the bottom. The header linefeature works just like the mode-line feature, except that it'scontrolled by different variables.@tindex header-line-format@defvar header-line-formatThis variable, local in every buffer, specifies how to display theheader line, for windows displaying the buffer. The format of the valueis the same as for @code{mode-line-format} (@pxref{Mode Line Data}).@end defvar@tindex default-header-line-format@defvar default-header-line-formatThis variable holds the default @code{header-line-format} for buffersthat do not override it. This is the same as @code{(default-value'header-line-format)}.It is normally @code{nil}, so that ordinary buffers have no header line.@end defvar@node Emulating Mode Line@subsection Emulating Mode-Line Formatting You can use the function @code{format-mode-line} to computethe text that would appear in a mode line or header linebased on certain mode-line specification.@defun format-mode-line &optional format window no-propsThis function formats a line of text according to @var{format} as ifit were generating the mode line for @var{window}, but instead ofdisplaying the text in the mode line or the header line, it returnsthe text as a string.If @var{format} is @code{nil}, that means to use@code{mode-line-format} and return the text that would appear in themode line. If @var{format} is @code{t}, that means to use@code{header-line-format} so as to return the text that would appearin the header line (@code{""} if the window has no header line).The argument @var{window} defaults to the selected window.The value string normally has text properties that correspond to thefaces, keymaps, etc., that the mode line would have. If@var{no-props} is non-@code{nil}, the value has no text properties.@end defun@node Imenu@section Imenu@cindex Imenu @dfn{Imenu} is a feature that lets users select a definition orsection in the buffer, from a menu which lists all of them, to godirectly to that location in the buffer. Imenu works by constructinga buffer index which lists the names and buffer positions of thedefinitions, or other named portions of the buffer; then the user canchoose one of them and move point to it. The user-level commands forusing Imenu are described in the Emacs Manual (@pxref{Imenu,, Imenu,emacs, the Emacs Manual}). This section explains how to customizeImenu's method of finding definitions or buffer portions for aparticular major mode. The usual and simplest way is to set the variable@code{imenu-generic-expression}:@defvar imenu-generic-expressionThis variable, if non-@code{nil}, is a list that specifies regularexpressions for finding definitions for Imenu. Simple elements of@code{imenu-generic-expression} look like this:@example(@var{menu-title} @var{regexp} @var{index})@end exampleHere, if @var{menu-title} is non-@code{nil}, it says that the matchesfor this element should go in a submenu of the buffer index;@var{menu-title} itself specifies the name for the submenu. If@var{menu-title} is @code{nil}, the matches for this element go directlyin the top level of the buffer index.The second item in the list, @var{regexp}, is a regular expression(@pxref{Regular Expressions}); anything in the buffer that it matchesis considered a definition, something to mention in the buffer index.The third item, @var{index}, is a non-negative integer that indicateswhich subexpression in @var{regexp} matches the definition's name.An element can also look like this:@example(@var{menu-title} @var{regexp} @var{index} @var{function} @var{arguments}@dots{})@end exampleLike in the previous case, each match for this element creates anindex item. However, if this index item is selected by the user, itcalls @var{function} with arguments consisting of the item name, thebuffer position, and @var{arguments}.For Emacs Lisp mode, @code{imenu-generic-expression} could look likethis:@c should probably use imenu-syntax-alist and \\sw rather than [-A-Za-z0-9+]@example@group((nil "^\\s-*(def\\(un\\|subst\\|macro\\|advice\\)\\\s-+\\([-A-Za-z0-9+]+\\)" 2)@end group@group ("*Vars*" "^\\s-*(def\\(var\\|const\\)\\\s-+\\([-A-Za-z0-9+]+\\)" 2)@end group@group ("*Types*" "^\\s-*\(def\\(type\\|struct\\|class\\|ine-condition\\)\\\s-+\\([-A-Za-z0-9+]+\\)" 2))@end group@end exampleSetting this variable makes it buffer-local in the current buffer.@end defvar@defvar imenu-case-fold-searchThis variable controls whether matching against the regularexpressions in the value of @code{imenu-generic-expression} iscase-sensitive: @code{t}, the default, means matching should ignorecase.Setting this variable makes it buffer-local in the current buffer.@end defvar@defvar imenu-syntax-alistThis variable is an alist of syntax table modifiers to use whileprocessing @code{imenu-generic-expression}, to override the syntax tableof the current buffer. Each element should have this form:@example(@var{characters} . @var{syntax-description})@end exampleThe @sc{car}, @var{characters}, can be either a character or a string.The element says to give that character or characters the syntaxspecified by @var{syntax-description}, which is passed to@code{modify-syntax-entry} (@pxref{Syntax Table Functions}).This feature is typically used to give word syntax to characters whichnormally have symbol syntax, and thus to simplify@code{imenu-generic-expression} and speed up matching.For example, Fortran mode uses it this way:@example(setq imenu-syntax-alist '(("_$" . "w")))@end exampleThe @code{imenu-generic-expression} regular expressions can then use@samp{\\sw+} instead of @samp{\\(\\sw\\|\\s_\\)+}. Note that thistechnique may be inconvenient when the mode needs to limit the initialcharacter of a name to a smaller set of characters than are allowed inthe rest of a name.Setting this variable makes it buffer-local in the current buffer.@end defvar Another way to customize Imenu for a major mode is to set thevariables @code{imenu-prev-index-position-function} and@code{imenu-extract-index-name-function}:@defvar imenu-prev-index-position-functionIf this variable is non-@code{nil}, its value should be a function thatfinds the next ``definition'' to put in the buffer index, scanningbackward in the buffer from point. It should return @code{nil} if itdoesn't find another ``definition'' before point. Otherwise it shouldleave point at the place it finds a ``definition,'' and return anynon-@code{nil} value.Setting this variable makes it buffer-local in the current buffer.@end defvar@defvar imenu-extract-index-name-functionIf this variable is non-@code{nil}, its value should be a function toreturn the name for a definition, assuming point is in that definitionas the @code{imenu-prev-index-position-function} function would leaveit.Setting this variable makes it buffer-local in the current buffer.@end defvar The last way to customize Imenu for a major mode is to set thevariable @code{imenu-create-index-function}:@defvar imenu-create-index-functionThis variable specifies the function to use for creating a bufferindex. The function should take no arguments, and return an indexalist for the current buffer. It is called within@code{save-excursion}, so where it leaves point makes no difference.The index alist can have three types of elements. Simple elementslook like this:@example(@var{index-name} . @var{index-position})@end exampleSelecting a simple element has the effect of moving to position@var{index-position} in the buffer. Special elements look like this:@example(@var{index-name} @var{index-position} @var{function} @var{arguments}@dots{})@end exampleSelecting a special element performs:@example(funcall @var{function} @var{index-name} @var{index-position} @var{arguments}@dots{})@end exampleA nested sub-alist element looks like this:@example(@var{menu-title} @var{sub-alist})@end exampleIt creates the submenu @var{menu-title} specified by @var{sub-alist}.The default value of @code{imenu-create-index-function} is@code{imenu-default-create-index-function}. This function uses@code{imenu-prev-index-position-function} and@code{imenu-extract-index-name-function} to produce the index alist.However, if either of these two variables is @code{nil}, the defaultfunction uses @code{imenu-generic-expression} instead.Setting this variable makes it buffer-local in the current buffer.@end defvar@node Font Lock Mode@section Font Lock Mode@cindex Font Lock Mode @dfn{Font Lock mode} is a feature that automatically attaches@code{face} properties to certain parts of the buffer based on theirsyntactic role. How it parses the buffer depends on the major mode;most major modes define syntactic criteria for which faces to use inwhich contexts. This section explains how to customize Font Lock for aparticular major mode. Font Lock mode finds text to highlight in two ways: through syntacticparsing based on the syntax table, and through searching (usually forregular expressions). Syntactic fontification happens first; it findscomments and string constants, and highlights them using@code{font-lock-comment-face} and @code{font-lock-string-face}(@pxref{Faces for Font Lock}). Search-based fontification follows.@menu* Font Lock Basics::* Search-based Fontification::* Other Font Lock Variables::* Levels of Font Lock::* Precalculated Fontification::* Faces for Font Lock::* Syntactic Font Lock::@end menu@node Font Lock Basics@subsection Font Lock Basics There are several variables that control how Font Lock mode highlightstext. But major modes should not set any of these variables directly.Instead, they should set @code{font-lock-defaults} as a buffer-localvariable. The value assigned to this variable is used, if and when FontLock mode is enabled, to set all the other variables.@defvar font-lock-defaultsThis variable is set by major modes, as a buffer-local variable, tospecify how to fontify text in that mode. The value should look likethis:@example(@var{keywords} @var{keywords-only} @var{case-fold} @var{syntax-alist} @var{syntax-begin} @var{other-vars}@dots{})@end exampleThe first element, @var{keywords}, indirectly specifies the value of@code{font-lock-keywords}. It can be a symbol, a variable whose valueis the list to use for @code{font-lock-keywords}. It can also be a list ofseveral such symbols, one for each possible level of fontification. Thefirst symbol specifies how to do level 1 fontification, the secondsymbol how to do level 2, and so on.The second element, @var{keywords-only}, specifies the value of thevariable @code{font-lock-keywords-only}. If this is non-@code{nil},syntactic fontification (of strings and comments) is not performed.The third element, @var{case-fold}, specifies the value of@code{font-lock-case-fold-search}. If it is non-@code{nil}, Font Lockmode ignores case when searching as directed by@code{font-lock-keywords}.If the fourth element, @var{syntax-alist}, is non-@code{nil}, it should bea list of cons cells of the form @code{(@var{char-or-string}. @var{string})}. These are used to set up a syntax table forfontification (@pxref{Syntax Table Functions}). The resulting syntaxtable is stored in @code{font-lock-syntax-table}.The fifth element, @var{syntax-begin}, specifies the value of@code{font-lock-beginning-of-syntax-function} (see below).All the remaining elements (if any) are collectively called@var{other-vars}. Each of these elements should have the form@code{(@var{variable} . @var{value})}---which means, make @var{variable}buffer-local and then set it to @var{value}. You can use these@var{other-vars} to set other variables that affect fontification,aside from those you can control with the first five elements.@end defvar@node Search-based Fontification@subsection Search-based Fontification The most important variable for customizing Font Lock mode is@code{font-lock-keywords}. It specifies the search criteria forsearch-based fontification.@defvar font-lock-keywordsThis variable's value is a list of the keywords to highlight. Becareful when composing regular expressions for this list; a poorlywritten pattern can dramatically slow things down!@end defvar Each element of @code{font-lock-keywords} specifies how to findcertain cases of text, and how to highlight those cases. Font Lock modeprocesses the elements of @code{font-lock-keywords} one by one, and foreach element, it finds and handles all matches. Ordinarily, oncepart of the text has been fontified already, this cannot be overriddenby a subsequent match in the same text; but you can specify differentbehavior using the @var{override} element of a @var{highlighter}. Each element of @code{font-lock-keywords} should have one of theseforms:@table @code@item @var{regexp}Highlight all matches for @var{regexp} using@code{font-lock-keyword-face}. For example,@example;; @r{Highlight discrete occurrences of @samp{foo}};; @r{using @code{font-lock-keyword-face}.}"\\<foo\\>"@end exampleThe function @code{regexp-opt} (@pxref{Syntax of Regexps}) is useful forcalculating optimal regular expressions to match a number of differentkeywords.@item @var{function}Find text by calling @var{function}, and highlight the matchesit finds using @code{font-lock-keyword-face}.When @var{function} is called, it receives one argument, the limit ofthe search; it should begin searching at point, and not search beyond thelimit. It should return non-@code{nil} if it succeeds, and set thematch data to describe the match that was found. Returning @code{nil}indicates failure of the search.Fontification will call @var{function} repeatedly with the same limit,and with point where the previous invocation left it, until@var{function} fails. On failure, @var{function} need not reset pointin any particular way.@item (@var{matcher} . @var{match})In this kind of element, @var{matcher} is either a regularexpression or a function, as described above. The @sc{cdr},@var{match}, specifies which subexpression of @var{matcher} should behighlighted (instead of the entire text that @var{matcher} matched).@example;; @r{Highlight the @samp{bar} in each occurrence of @samp{fubar},};; @r{using @code{font-lock-keyword-face}.}("fu\\(bar\\)" . 1)@end exampleIf you use @code{regexp-opt} to produce the regular expression@var{matcher}, then you can use @code{regexp-opt-depth} (@pxref{Syntaxof Regexps}) to calculate the value for @var{match}.@item (@var{matcher} . @var{facespec})In this kind of element, @var{facespec} is an object which specifiesthe face variable to use for highlighting. In the simplest case, itis a Lisp variable (a symbol), whose value should be a face name.@example;; @r{Highlight occurrences of @samp{fubar},};; @r{using the face which is the value of @code{fubar-face}.}("fubar" . fubar-face)@end exampleHowever, @var{facespec} can also be a list of the form@example(face @var{face} @var{prop1} @var{val1} @var{prop2} @var{val2}@dots{})@end exampleto specify various text properties to put on the text that matches.If you do this, be sure to add the other text property names that youset in this way to the value of @code{font-lock-extra-managed-props}so that the properties will also be cleared out when they are no longerappropriate.@item (@var{matcher} . @var{highlighter})In this kind of element, @var{highlighter} is a listwhich specifies how to highlight matches found by @var{matcher}.It has the form@example(@var{subexp} @var{facespec} @var{override} @var{laxmatch})@end exampleThe @sc{car}, @var{subexp}, is an integer specifying which subexpressionof the match to fontify (0 means the entire matching text). The secondsubelement, @var{facespec}, specifies the face, as described above.The last two values in @var{highlighter}, @var{override} and@var{laxmatch}, are flags. If @var{override} is @code{t}, thiselement can override existing fontification made by previous elementsof @code{font-lock-keywords}. If it is @code{keep}, then eachcharacter is fontified if it has not been fontified already by someother element. If it is @code{prepend}, the face specified by@var{facespec} is added to the beginning of the @code{font-lock-face}property. If it is @code{append}, the face is added to the end of the@code{font-lock-face} property.If @var{laxmatch} is non-@code{nil}, it means there should be no errorif there is no subexpression numbered @var{subexp} in @var{matcher}.Obviously, fontification of the subexpression numbered @var{subexp} willnot occur. However, fontification of other subexpressions (and otherregexps) will continue. If @var{laxmatch} is @code{nil}, and thespecified subexpression is missing, then an error is signalled whichterminates search-based fontification.Here are some examples of elements of this kind, and what they do:@smallexample;; @r{Highlight occurrences of either @samp{foo} or @samp{bar},};; @r{using @code{foo-bar-face}, even if they have already been highlighted.};; @r{@code{foo-bar-face} should be a variable whose value is a face.}("foo\\|bar" 0 foo-bar-face t);; @r{Highlight the first subexpression within each occurrence};; @r{that the function @code{fubar-match} finds,};; @r{using the face which is the value of @code{fubar-face}.}(fubar-match 1 fubar-face)@end smallexample@item (@var{matcher} @var{highlighters}@dots{})This sort of element specifies several @var{highlighter} lists for asingle @var{matcher}. In order for this to be useful, each@var{highlighter} should have a different value of @var{subexp}; that is,each one should apply to a different subexpression of @var{matcher}.@ignore@item (@var{matcher} . @var{anchored})In this kind of element, @var{anchored} acts much like a@var{highlighter}, but it is more complex and can specify multiplesuccessive searches.For highlighting single items, typically only @var{highlighter} isrequired. However, if an item or (typically) items are to behighlighted following the instance of another item (the anchor) then@var{anchored} may be required.It has this format:@example(@var{submatcher} @var{pre-match-form} @var{post-match-form} @var{highlighters}@dots{})@end example@c I can't parse this text -- rmswhere @var{submatcher} is much like @var{matcher}, with oneexception---see below. @var{pre-match-form} and @var{post-match-form}are evaluated before the first, and after the last, instance@var{anchored}'s @var{submatcher} is used. Therefore they can be usedto initialize before, and cleanup after, @var{submatcher} is used.Typically, @var{pre-match-form} is used to move to some positionrelative to the original @var{submatcher}, before starting with@var{anchored}'s @var{submatcher}. @var{post-match-form} might be usedto move, before resuming with @var{anchored}'s parent's @var{matcher}.For example, an element of the form highlights (if not already highlighted):@example("\\<anchor\\>" (0 anchor-face) ("\\<item\\>" nil nil (0 item-face)))@end exampleDiscrete occurrences of @samp{anchor} in the value of@code{anchor-face}, and subsequent discrete occurrences of @samp{item}(on the same line) in the value of @code{item-face}. (Here@var{pre-match-form} and @var{post-match-form} are @code{nil}.Therefore @samp{item} is initially searched for starting from the end ofthe match of @samp{anchor}, and searching for subsequent instance of@samp{anchor} resumes from where searching for @samp{item} concluded.)The above-mentioned exception is as follows. The limit of the@var{submatcher} search defaults to the end of the line after@var{pre-match-form} is evaluated. However, if @var{pre-match-form}returns a position greater than the position after @var{pre-match-form}is evaluated, that position is used as the limit of the search. It isgenerally a bad idea to return a position greater than the end of theline; in other words, the @var{submatcher} search should not span lines.@item (@var{matcher} @var{highlighters-or-anchoreds} ...)@end ignore@item (eval . @var{form})Here @var{form} is an expression to be evaluated the first timethis value of @code{font-lock-keywords} is used in a buffer.Its value should have one of the forms described in this table.@end table@strong{Warning:} Do not design an element of @code{font-lock-keywords}to match text which spans lines; this does not work reliably. While@code{font-lock-fontify-buffer} handles multi-line patterns correctly,updating when you edit the buffer does not, since it considers text oneline at a time. If you have patterns that typically only span oneline but can occasionally span two or three, such as@samp{<title>...</title>}, you can ask font-lock to be more careful bysetting @code{font-lock-multiline} to @code{t}. But it still will notwork in all cases.@node Other Font Lock Variables@subsection Other Font Lock Variables This section describes additional variables that a major modecan set by means of @code{font-lock-defaults}.@defvar font-lock-keywords-onlyNon-@code{nil} means Font Lock should not fontify comments or stringssyntactically; it should only fontify based on@code{font-lock-keywords}.@end defvar@ignoreOther variables include those for buffer-specialized fontification functions,`font-lock-fontify-buffer-function', `font-lock-unfontify-buffer-function',`font-lock-fontify-region-function', `font-lock-unfontify-region-function',`font-lock-inhibit-thing-lock' and `font-lock-maximum-size'.@end ignore@defvar font-lock-keywords-case-fold-searchNon-@code{nil} means that regular expression matching for the sake of@code{font-lock-keywords} should be case-insensitive.@end defvar@defvar font-lock-syntax-tableThis variable specifies the syntax table to use for fontification ofcomments and strings.@end defvar@defvar font-lock-beginning-of-syntax-functionIf this variable is non-@code{nil}, it should be a function to movepoint back to a position that is syntactically at ``top level'' andoutside of strings or comments. Font Lock uses this when necessaryto get the right results for syntactic fontification.This function is called with no arguments. It should leave point at thebeginning of any enclosing syntactic block. Typical values are@code{beginning-of-line} (i.e., the start of the line is known to beoutside a syntactic block), or @code{beginning-of-defun} for programmingmodes or @code{backward-paragraph} for textual modes (i.e., themode-dependent function is known to move outside a syntactic block).If the value is @code{nil}, the beginning of the buffer is used as aposition outside of a syntactic block. This cannot be wrong, but it canbe slow.@end defvar@defvar font-lock-mark-block-functionIf this variable is non-@code{nil}, it should be a function that iscalled with no arguments, to choose an enclosing range of text forrefontification for the command @kbd{M-g M-g}(@code{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 valuesare @code{mark-defun} for programming modes or @code{mark-paragraph} fortextual modes.@end defvar@defvar font-lock-extra-managed-propsAdditional properties (other than @code{font-lock-face}) that arebeing managed by Font Lock mode. Font Lock mode normally manages onlythe @code{font-lock-face} property; if you want it to manage others aswell, you must specify them in a @var{facespec} in@code{font-lock-keywords} as well as adding them to this list.@end defvar@defvar font-lock-syntactic-face-functionA function to determine which face to use for a given syntacticelement (a string or a comment). The function is called with oneargument, the parse state at point returned by@code{parse-partial-sexp}, and should return a face. The defaultvalue returns @code{font-lock-comment-face} for comments and@code{font-lock-string-face} for strings.This can be used to highlighting different kinds of strings orcomments differently. It is also sometimes abused together with@code{font-lock-syntactic-keywords} to highlight elements that spanmultiple lines, but this is too obscure to document in this manual.@end defvar@node Levels of Font Lock@subsection Levels of Font Lock Many major modes offer three different levels of fontification. Youcan define multiple levels by using a list of symbols for @var{keywords}in @code{font-lock-defaults}. Each symbol specifies one level offontification; it is up to the user to choose one of these levels. Thechosen level's symbol value is used to initialize@code{font-lock-keywords}. Here are the conventions for how to define the levels offontification:@itemize @bullet@itemLevel 1: highlight function declarations, file directives (such as include orimport directives), strings and comments. The idea is speed, so onlythe most important and top-level components are fontified.@itemLevel 2: in addition to level 1, highlight all language keywords,including type names that act like keywords, as well as named constantvalues. The idea is that all keywords (either syntactic or semantic)should be fontified appropriately.@itemLevel 3: in addition to level 2, highlight the symbols being defined infunction and variable declarations, and all builtin function names,wherever they appear.@end itemize@node Precalculated Fontification@subsection Precalculated FontificationIn addition to using @code{font-lock-defaults} for search-basedfontification, you may use the special character property@code{font-lock-face} (@pxref{Special Properties}). This propertyacts just like the explicit @code{face} property, but its activationis toggled when the user calls @kbd{M-x font-lock-mode}. Using@code{font-lock-face} is especially convenient for special modeswhich construct their text programmatically, such as@code{list-buffers} and @code{occur}.If your mode does not use any of the other machinery of Font Lock(i.e. it only uses the @code{font-lock-face} property), you can tellEmacs not to load all of font-lock.el (unless it's already loaded), bysetting the variable @code{font-lock-core-only} to non-@code{nil} aspart of the @code{font-lock-defaults} settings. Here is the canonicalway to do this:@example(set (make-local-variable 'font-lock-defaults) '(nil t nil nil nil (font-lock-core-only . t)))@end example@node Faces for Font Lock@subsection Faces for Font Lock You can make Font Lock mode use any face, but several faces aredefined specifically for Font Lock mode. Each of these symbols is botha face name, and a variable whose default value is the symbol itself.Thus, the default value of @code{font-lock-comment-face} is@code{font-lock-comment-face}. This means you can write@code{font-lock-comment-face} in a context such as@code{font-lock-keywords} where a face-name-valued expression is used.@table @code@item font-lock-comment-face@vindex font-lock-comment-faceUsed (typically) for comments.@item font-lock-string-face@vindex font-lock-string-faceUsed (typically) for string constants.@item font-lock-keyword-face@vindex font-lock-keyword-faceUsed (typically) for keywords---names that have special syntacticsignificance, like @code{for} and @code{if} in C.@item font-lock-builtin-face@vindex font-lock-builtin-faceUsed (typically) for built-in function names.@item font-lock-function-name-face@vindex font-lock-function-name-faceUsed (typically) for the name of a function being defined or declared,in a function definition or declaration.@item font-lock-variable-name-face@vindex font-lock-variable-name-faceUsed (typically) for the name of a variable being defined or declared,in a variable definition or declaration.@item font-lock-type-face@vindex font-lock-type-faceUsed (typically) for names of user-defined data types,where they are defined and where they are used.@item font-lock-constant-face@vindex font-lock-constant-faceUsed (typically) for constant names.@item font-lock-preprocessor-face@vindex font-lock-preprocessor-faceUsed (typically) for preprocessor commands.@item font-lock-warning-face@vindex font-lock-warning-faceUsed (typically) for constructs that are peculiar, or that greatlychange the meaning of other text. For example, this is used for@samp{;;;###autoload} cookies in Emacs Lisp, and for @code{#error}directives in C.@end table@node Syntactic Font Lock@subsection Syntactic Font Lock Font Lock mode can be used to update @code{syntax-table} propertiesautomatically. This is useful in languages for which a single syntaxtable by itself is not sufficient.@defvar font-lock-syntactic-keywordsThis variable enables and controls syntactic Font Lock. It isnormally set via @code{font-lock-defaults}. Its value should be alist of elements of this form:@example(@var{matcher} @var{subexp} @var{syntax} @var{override} @var{laxmatch})@end exampleThe parts of this element have the same meanings as in the correspondingsort of element of @code{font-lock-keywords},@example(@var{matcher} @var{subexp} @var{facename} @var{override} @var{laxmatch})@end exampleHowever, instead of specifying the value @var{facename} to use for the@code{face} property, it specifies the value @var{syntax} to use forthe @code{syntax-table} property. Here, @var{syntax} can be a string(as taken by @code{modify-syntax-entry}), a syntax table, a cons cell(as returned by @code{string-to-syntax}), or an expression whose valueis one of those two types. @var{override} cannot be @code{prepend} or@code{append}.For example, an element of the form:@example("\\$\\(#\\)" 1 ".")@end examplehighlights syntactically a hash character when following a dollarcharacter, with a SYNTAX of @code{"."} (meaning punctuation syntax).Assuming that the buffer syntax table specifies hash characters tohave comment start syntax, the element will only highlight hashcharacters that do not follow dollar characters as commentssyntactically.An element of the form:@example ("\\('\\).\\('\\)" (1 "\"") (2 "\""))@end examplehighlights syntactically both single quotes which surround a singlecharacter, with a SYNTAX of @code{"\""} (meaning string quote syntax).Assuming that the buffer syntax table does not specify single quotesto have quote syntax, the element will only highlight single quotes ofthe form @samp{'@var{c}'} as strings syntactically. Other forms, suchas @samp{foo'bar} or @samp{'fubar'}, will not be highlighted asstrings.@end defvar@node Desktop Save Mode@section Desktop Save Mode@cindex desktop save mode@dfn{Desktop Save Mode} is a feature to save the state of Emacs fromone session to another. The user-level commands for using DesktopSave Mode are described in the GNU Emacs Manual (@pxref{Saving EmacsSessions,,, emacs, the GNU Emacs Manual}). Modes whose buffers visita file, don't have to do anything to use this feature.For buffers not visiting a file to have their state saved, the majormode must bind the buffer local variable @code{desktop-save-buffer} toa non-nil value.@defvar desktop-save-bufferIf this buffer-local variable is non-@code{nil}, the buffer will haveits state saved in the desktop file at desktop save. If the value isa function, it is called at desktop save with argument@var{desktop-dirname}, and its value is saved in the desktop file alongwith the state of the buffer for which it was called. When file namesare returned as part of the auxiliary information, they should beformatted using the call@example(desktop-file-name @var{file-name} @var{desktop-dirname})@end example@end defvarFor buffers not visiting a file to be restored, the major mode mustdefine a function to do the job, and that function must be listed inthe alist @code{desktop-buffer-mode-handlers}.@defvar desktop-buffer-mode-handlersAlist with elements@example(@var{major-mode} . @var{restore-buffer-function})@end exampleThe function @var{restore-buffer-function} will be called withargument list@example(@var{buffer-file-name} @var{buffer-name} @var{desktop-buffer-misc})@end exampleand it should return the restored buffer.Here @var{desktop-buffer-misc} is the value returned by the functionoptionally bound to @code{desktop-save-buffer}.@end defvar@node Hooks@section Hooks@cindex hooks A @dfn{hook} is a variable where you can store a function or functionsto be called on a particular occasion by an existing program. Emacsprovides hooks for the sake of customization. Most often, hooks are setup in the init file (@pxref{Init File}), but Lisp programs can set them also.@xref{Standard Hooks}, for a list of standard hook variables.@cindex normal hook Most of the hooks in Emacs are @dfn{normal hooks}. These variablescontain lists of functions to be called with no arguments. When thehook name ends in @samp{-hook}, that tells you it is normal. We try tomake all hooks normal, as much as possible, so that you can use them ina uniform way. Every major mode function is supposed to run a normal hook called the@dfn{mode hook} as the last step of initialization. This makes it easyfor a user to customize the behavior of the mode, by overriding thebuffer-local variable assignments already made by the mode. But hooksare used in other contexts too. For example, the hook@code{suspend-hook} runs just before Emacs suspends itself(@pxref{Suspending Emacs}). The recommended way to add a hook function to a normal hook is bycalling @code{add-hook} (see below). The hook functions may be any ofthe valid kinds of functions that @code{funcall} accepts (@pxref{WhatIs a Function}). Most normal hook variables are initially void;@code{add-hook} knows how to deal with this. You can add hooks eitherglobally or buffer-locally with @code{add-hook}.@cindex abnormal hook If the hook variable's name does not end with @samp{-hook}, thatindicates it is probably an @dfn{abnormal hook}. Then you should look at itsdocumentation to see how to use the hook properly. If the variable's name ends in @samp{-functions} or @samp{-hooks},then the value is a list of functions, but it is abnormal in that eitherthese functions are called with arguments or their values are used insome way. You can use @code{add-hook} to add a function to the list,but you must take care in writing the function. (A few of thesevariables, notably those ending in @samp{-hooks}, are actuallynormal hooks which were named before we established the convention ofusing @samp{-hook} for them.) If the variable's name ends in @samp{-function}, then its valueis just a single function, not a list of functions. Here's an example that uses a mode hook to turn on Auto Fill mode whenin Lisp Interaction mode:@example(add-hook 'lisp-interaction-mode-hook 'turn-on-auto-fill)@end example At the appropriate time, Emacs uses the @code{run-hooks} function torun particular hooks. This function calls the hook functions that havebeen added with @code{add-hook}.@defun run-hooks &rest hookvarsThis function takes one or more normal hook variable names asarguments, and runs each hook in turn. Each argument should be asymbol that is a normal hook variable. These arguments are processedin the order specified.If a hook variable has a non-@code{nil} value, that value may be afunction or a list of functions. (The former option is consideredobsolete.) If the value is a function (either a lambda expression ora symbol with a function definition), it is called. If it is a listthat isn't a function, its elements are called, consecutively. Allthe hook functions are called with no arguments.For example, here's how @code{emacs-lisp-mode} runs its mode hook:@example(run-hooks 'emacs-lisp-mode-hook)@end example@end defun@defun run-mode-hooks &rest hookvarsLike @code{run-hooks}, but is affected by the @code{delay-mode-hooks}macro.@end defun@defmac delay-mode-hooks body...This macro executes the @var{body} forms but defers all calls to@code{run-mode-hooks} within them until the end of @var{body}.This macro enables a derived mode to arrange not to runits parent modes' mode hooks until the end.@end defmac@defun run-hook-with-args hook &rest argsThis function is the way to run an abnormal hook and always call allof the hook functions. It calls each of the hook functions one byone, passing each of them the arguments @var{args}.@end defun@defun run-hook-with-args-until-failure hook &rest argsThis function is the way to run an abnormal hook until one of the hookfunctions fails. It calls each of the hook functions, passing each ofthem the arguments @var{args}, until some hook function returns@code{nil}. It then stops and returns @code{nil}. If none of thehook functions return @code{nil}, it returns a non-@code{nil} value.@end defun@defun run-hook-with-args-until-success hook &rest argsThis function is the way to run an abnormal hook until a hook functionsucceeds. It calls each of the hook functions, passing each of themthe arguments @var{args}, until some hook function returnsnon-@code{nil}. Then it stops, and returns whatever was returned bythe last hook function that was called. If all hook functions return@code{nil}, it returns @code{nil} as well.@end defun@defun add-hook hook function &optional append localThis function is the handy way to add function @var{function} to hookvariable @var{hook}. You can use it for abnormal hooks as well as fornormal hooks. @var{function} can be any Lisp function that can acceptthe proper number of arguments for @var{hook}. For example,@example(add-hook 'text-mode-hook 'my-text-hook-function)@end example@noindentadds @code{my-text-hook-function} to the hook called @code{text-mode-hook}.If @var{function} is already present in @var{hook} (comparing using@code{equal}), then @code{add-hook} does not add it a second time.It is best to design your hook functions so that the order in which theyare executed does not matter. Any dependence on the order is ``askingfor trouble''. However, the order is predictable: normally,@var{function} goes at the front of the hook list, so it will beexecuted first (barring another @code{add-hook} call). If the optionalargument @var{append} is non-@code{nil}, the new hook function goes atthe end of the hook list and will be executed last.If @var{local} is non-@code{nil}, that says to add @var{function} tothe buffer-local hook list instead of to the global hook list. Ifneeded, this makes the hook buffer-local and adds @code{t} to thebuffer-local value. The latter acts as a flag to run the hookfunctions in the default value as well as in the local value.@end defun@defun remove-hook hook function &optional localThis function removes @var{function} from the hook variable@var{hook}. It compares @var{function} with elements of @var{hook}using @code{equal}, so it works for both symbols and lambdaexpressions.If @var{local} is non-@code{nil}, that says to remove @var{function}from the buffer-local hook list instead of from the global hook list.@end defun@ignore arch-tag: 4c7bff41-36e6-4da6-9e7f-9b9289e27c8e@end ignore