modes.texi 129 KB
Newer Older
Glenn Morris's avatar
Glenn Morris committed
1 2 3
@c -*-texinfo-*-
@c This is part of the GNU Emacs Lisp Reference Manual.
@c Copyright (C) 1990, 1991, 1992, 1993, 1994, 1995, 1998, 1999, 2001,
Glenn Morris's avatar
Glenn Morris committed
4
@c   2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009  Free Software Foundation, Inc.
Glenn Morris's avatar
Glenn Morris committed
5
@c See the file elisp.texi for copying conditions.
6
@setfilename ../../info/modes
Glenn Morris's avatar
Glenn Morris committed
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
@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 be
turned on and off while you edit.  There are two varieties of modes:
@dfn{major modes}, which are mutually exclusive and used for editing
particular kinds of text, and @dfn{minor modes}, which provide features
that users can enable individually.

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

@menu
* Hooks::              How to use hooks; how to write code that provides hooks.
* 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.
@end menu

@node Hooks
@section Hooks
@cindex hooks

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

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

  Every major mode function is supposed to run a normal hook called
the @dfn{mode hook} as the one of the last steps of initialization.
This makes it easy for a user to customize the behavior of the mode,
by overriding the buffer-local variable assignments already made by
the mode.  Most minor mode functions also run a mode hook at the end.
But hooks are used in other contexts too.  For example, the hook
@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 by
calling @code{add-hook} (see below).  The hook functions may be any of
the valid kinds of functions that @code{funcall} accepts (@pxref{What
Is a Function}).  Most normal hook variables are initially void;
@code{add-hook} knows how to deal with this.  You can add hooks either
globally or buffer-locally with @code{add-hook}.

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

  By convention, abnormal hook names end in @samp{-functions} or
@samp{-hooks}.  If the variable's name ends in @samp{-function}, then
its value is just a single function, not a list of functions.

80 81 82 83
@menu
* Running Hooks::      How to run a hook.
* Setting Hooks::      How to put functions on a hook, or remove them.
@end menu
Glenn Morris's avatar
Glenn Morris committed
84

85 86
@node Running Hooks
@subsection Running Hooks
Glenn Morris's avatar
Glenn Morris committed
87

88 89
  At the appropriate times, Emacs uses the @code{run-hooks} function
and the other functions below to run particular hooks.
Glenn Morris's avatar
Glenn Morris committed
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128

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

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

The hook variable's value can also be a single function---either a
lambda expression or a symbol with a function definition---which
@code{run-hooks} calls.  But this usage is obsolete.
@end defun

@defun run-hook-with-args hook &rest args
This function is the way to run an abnormal hook and always call all
of the hook functions.  It calls each of the hook functions one by
one, passing each of them the arguments @var{args}.
@end defun

@defun run-hook-with-args-until-failure hook &rest args
This function is the way to run an abnormal hook until one of the hook
functions fails.  It calls each of the hook functions, passing each of
them the arguments @var{args}, until some hook function returns
@code{nil}.  It then stops and returns @code{nil}.  If none of the
hook functions return @code{nil}, it returns a non-@code{nil} value.
@end defun

@defun run-hook-with-args-until-success hook &rest args
This function is the way to run an abnormal hook until a hook function
succeeds.  It calls each of the hook functions, passing each of them
the arguments @var{args}, until some hook function returns
non-@code{nil}.  Then it stops, and returns whatever was returned by
the last hook function that was called.  If all hook functions return
@code{nil}, it returns @code{nil} as well.
@end defun

129 130 131 132 133 134 135 136 137 138
@node Setting Hooks
@subsection Setting Hooks

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

@example
(add-hook 'lisp-interaction-mode-hook 'turn-on-auto-fill)
@end example

Glenn Morris's avatar
Glenn Morris committed
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
@defun add-hook hook function &optional append local
This function is the handy way to add function @var{function} to hook
variable @var{hook}.  You can use it for abnormal hooks as well as for
normal hooks.  @var{function} can be any Lisp function that can accept
the proper number of arguments for @var{hook}.  For example,

@example
(add-hook 'text-mode-hook 'my-text-hook-function)
@end example

@noindent
adds @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.

155 156 157 158 159
If @var{function} has a non-@code{nil} property
@code{permanent-local-hook}, then @code{kill-all-local-variables} (or
changing major modes) won't delete it from the hook variable's local
value.

160 161 162
It is best to design your hook functions so that the order in which
they are executed does not matter.  Any dependence on the order is
asking for trouble.  However, the order is predictable: normally,
Glenn Morris's avatar
Glenn Morris committed
163
@var{function} goes at the front of the hook list, so it will be
164 165 166
executed first (barring another @code{add-hook} call).  If the
optional argument @var{append} is non-@code{nil}, the new hook
function goes at the end of the hook list and will be executed last.
Glenn Morris's avatar
Glenn Morris committed
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233

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

If @var{local} is non-@code{nil}, that says to add @var{function} to
the buffer-local hook list instead of to the global hook list.  If
needed, this makes the hook buffer-local and adds @code{t} to the
buffer-local value.  The latter acts as a flag to run the hook
functions in the default value as well as in the local value.
@end defun

@defun remove-hook hook function &optional local
This 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 lambda
expressions.

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

@node Major Modes
@section Major Modes
@cindex major mode

  Major modes specialize Emacs for editing particular kinds of text.
Each buffer has only one major mode at a time.  For each major mode
there is a function to switch to that mode in the current buffer; its
name should end in @samp{-mode}.  These functions work by setting
buffer-local variable bindings and other data associated with the
buffer, such as a local keymap.  The effect lasts until you switch
to another major mode in the same buffer.

@menu
* Major Mode Basics::
* Major Mode Conventions::  Coding conventions for keymaps, etc.
* 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.
* Generic Modes::           Defining a simple major mode that supports
                              comment syntax and Font Lock mode.
* Mode Hooks::              Hooks run at the end of major mode functions.
* Example Major Modes::     Text mode and Lisp modes.
@end menu

@node Major Mode Basics
@subsection Major Mode Basics
@cindex Fundamental mode

  The least specialized major mode is called @dfn{Fundamental mode}.
This mode has no mode-specific definitions or variable settings, so each
Emacs command behaves in its default manner, and each option is in its
default state.  All other major modes redefine various keys and options.
For example, Lisp Interaction mode provides special key bindings for
@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 a
specialized editing task, creating a new major mode is usually a good
idea.  In practice, writing a major mode is easy (in contrast to
writing a minor mode, which is often difficult).

  If the new mode is similar to an old one, it is often unwise to
modify the old one to serve two purposes, since it may become harder
to use and maintain.  Instead, copy and rename an existing major mode
234 235 236 237 238
definition and alter the copy---or use the @code{define-derived-mode}
macro to define a @dfn{derived mode} (@pxref{Derived Modes}).  For
example, Rmail Edit mode is a major mode that is very similar to Text
mode except that it provides two additional commands.  Its definition
is distinct from that of Text mode, but uses that of Text mode.
Glenn Morris's avatar
Glenn Morris committed
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319

  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 important
coding conventions for you.

  For a very simple programming language major mode that handles
comments and fontification, you can use @code{define-generic-mode}.
@xref{Generic Modes}.

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

  The standard GNU Emacs Lisp library directory tree contains the code
for 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 modes
are written.  Text mode is perhaps the simplest major mode aside from
Fundamental mode.  Rmail mode is a complicated and specialized mode.

@node Major Mode Conventions
@subsection Major Mode Conventions
@cindex major mode conventions
@cindex conventions for writing major modes

  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 you
define a new major mode.  (Fundamental mode is an exception to many
of these conventions, because its definition is to present the global
state of Emacs.)

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

@itemize @bullet
@item
Define a command whose name ends in @samp{-mode}, with no arguments,
that switches to the new mode in the current buffer.  This command
should set up the keymap, syntax table, and buffer-local variables in an
existing buffer, without changing the buffer's contents.

@item
Write a documentation string for this command that describes the
special 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 documentation
substrings, @samp{\[@var{command}]}, @samp{\@{@var{keymap}@}}, and
@samp{\<@var{keymap}>}, which enable the documentation to adapt
automatically to the user's own key bindings.  @xref{Keys in
Documentation}.

@item
The major mode command should start by calling
@code{kill-all-local-variables}.  This runs the normal hook
@code{change-major-mode-hook}, then gets rid of the buffer-local
variables of the major mode previously in effect.  @xref{Creating
Buffer-Local}.

@item
The major mode command should set the variable @code{major-mode} to the
major mode command symbol.  This is how @code{describe-mode} discovers
which documentation to print.

@item
The major mode command should set the variable @code{mode-name} to the
320 321 322
``pretty'' name of the mode, usually a string (but see @ref{Mode Line
Data}, for other possible forms).  The name of the mode appears
in the mode line.
Glenn Morris's avatar
Glenn Morris committed
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378

@item
@cindex functions in modes
Since all global names are in the same name space, all the global
variables, constants, and functions that are part of the mode should
have names that start with the major mode name (or with an abbreviation
of it if the name is long).  @xref{Coding Conventions}.

@item
In a major mode for editing some kind of structured text, such as a
programming language, indentation of text according to structure is
probably useful.  So the mode should set @code{indent-line-function}
to a suitable function, and probably customize other variables
for indentation.

@item
@cindex keymaps in modes
The major mode should usually have its own keymap, which is used as the
local keymap in all buffers in that mode.  The major mode command should
call @code{use-local-map} to install this local map.  @xref{Active
Keymaps}, for more information.

This keymap should be stored permanently in a global variable named
@code{@var{modename}-mode-map}.  Normally the library that defines the
mode sets this variable.

@xref{Tips for Defining}, for advice about how to write the code to set
up the mode's keymap variable.

@item
The 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 punctuation
characters are reserved for minor modes, and ordinary letters are
reserved 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 normally
be some kind of ``moving forward and backward,'' but this does not
necessarily mean cursor motion.

It is legitimate for a major mode to rebind a standard key sequence if
it provides a command that does ``the same job'' in a way better
suited to the text this mode is used for.  For example, a major mode
for editing a programming language might redefine @kbd{C-M-a} to
``move to the beginning of a function'' in a way that works better for
that language.

It is also legitimate for a major mode to rebind a standard key
sequence whose standard meaning is rarely useful in that mode.  For
instance, minibuffer modes rebind @kbd{M-r}, whose standard meaning is
rarely of any use in the minibuffer.  Major modes such as Dired or
Rmail that do not allow self-insertion of text can reasonably redefine
letters and other printing characters as special commands.

@item
Juanma Barranquero's avatar
Juanma Barranquero committed
379
Major modes for editing text should not define @key{RET} to do
Glenn Morris's avatar
Glenn Morris committed
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
anything other than insert a newline.  However, it is ok for
specialized modes for text that users don't directly edit, such as
Dired and Info modes, to redefine @key{RET} to do something entirely
different.

@item
Major modes should not alter options that are primarily a matter of user
preference, such as whether Auto-Fill mode is enabled.  Leave this to
each user to decide.  However, a major mode should customize other
variables so that Auto-Fill mode will work usefully @emph{if} the user
decides to use it.

@item
@cindex syntax tables in modes
The mode may have its own syntax table or may share one with other
related modes.  If it has its own syntax table, it should store this in
a variable named @code{@var{modename}-mode-syntax-table}.  @xref{Syntax
Tables}.

@item
If the mode handles a language that has a syntax for comments, it should
set the variables that define the comment syntax.  @xref{Options for
Comments,, Options Controlling Comments, emacs, The GNU Emacs Manual}.

@item
@cindex abbrev tables in modes
The mode may have its own abbrev table or may share one with other
related modes.  If it has its own abbrev table, it should store this
in a variable named @code{@var{modename}-mode-abbrev-table}.  If the
major mode command defines any abbrevs itself, it should pass @code{t}
for the @var{system-flag} argument to @code{define-abbrev}.
@xref{Defining Abbrevs}.

@item
The mode should specify how to do highlighting for Font Lock mode, by
setting up a buffer-local value for the variable
@code{font-lock-defaults} (@pxref{Font Lock Mode}).

@item
The mode should specify how Imenu should find the definitions or
sections of a buffer, by setting up a buffer-local value for the
variable @code{imenu-generic-expression}, for the two 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}).

@item
The mode can specify a local value for
@code{eldoc-documentation-function} to tell ElDoc mode how to handle
this mode.

@item
Use @code{defvar} or @code{defcustom} to set mode-related variables, so
that they are not reinitialized if they already have a value.  (Such
reinitialization could discard customizations made by the user.)

@item
@cindex buffer-local variables in modes
To 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 the
variable local to every buffer in which it is subsequently set, which
would affect buffers that do not use this mode.  It is undesirable for a
mode to have such global effects.  @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 variable
which is used only within that package.  Using it on a variable used by
other packages would interfere with them.

@item
@cindex mode hook
@cindex major mode hook
Each major mode should have a normal @dfn{mode hook} named
@code{@var{modename}-mode-hook}.  The very last thing the major mode command
should do is to call @code{run-mode-hooks}.  This runs the mode hook,
and then runs the normal hook @code{after-change-major-mode-hook}.
@xref{Mode Hooks}.

@item
The major mode command may start by calling some other major mode
command (called the @dfn{parent mode}) and then alter some of its
settings.  A mode that does this is called a @dfn{derived mode}.  The
463 464 465
recommended way to define one is to use the @code{define-derived-mode}
macro, but this is not required.  Such a mode should call the parent
mode command inside a @code{delay-mode-hooks} form.  (Using
Glenn Morris's avatar
Glenn Morris committed
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
@code{define-derived-mode} does this automatically.)  @xref{Derived
Modes}, and @ref{Mode Hooks}.

@item
If something special should be done if the user switches a buffer from
this mode to any other major mode, this mode can set up a buffer-local
value for @code{change-major-mode-hook} (@pxref{Creating Buffer-Local}).

@item
If this mode is appropriate only for specially-prepared text, then the
major 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

@noindent
This tells Emacs that new buffers created while the current buffer is
487 488
in Funny mode should not inherit Funny mode, in case the default value
of @code{major-mode} is @code{nil}.  Modes such as Dired, Rmail,
Glenn Morris's avatar
Glenn Morris committed
489 490
and Buffer List use this feature.

491 492 493 494 495 496
The @code{define-derived-mode} macro automatically marks the derived
mode as special if the parent mode is special.  The special mode
@code{special-mode} provides a convenient parent for other special
modes to inherit from; it sets @code{buffer-read-only} to @code{t},
and does nothing else.

Glenn Morris's avatar
Glenn Morris committed
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
@item
If you want to make the new mode the default for files with certain
recognizable names, add an element to @code{auto-mode-alist} to select
the mode for those file names (@pxref{Auto Major Mode}).  If you
define the mode command to autoload, you should add this element in
the same file that calls @code{autoload}.  If you use an autoload
cookie for the mode command, you can also use an autoload cookie for
the form that adds the element (@pxref{autoload cookie}).  If you do
not autoload the mode command, it is sufficient to add the element in
the file that contains the mode definition.

@item
In the comments that document the file, you should provide a sample
@code{autoload} form and an example of how to add to
@code{auto-mode-alist}, that users can include in their init files
(@pxref{Init File}).

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

@node Auto Major Mode
@subsection How Emacs Chooses a Major Mode
@cindex major mode, automatic selection

  Based on information in the file name or in the file itself, Emacs
automatically selects a major mode for the new buffer when a file is
visited.  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 anything
in particular.  Other major modes are defined in effect by comparison
with this one---their definitions say what to change, starting from
Fundamental mode.  The @code{fundamental-mode} function does @emph{not}
run any mode hooks; you're not supposed to customize it.  (If you want Emacs
to behave differently in Fundamental mode, change the @emph{global}
state of Emacs.)
@end deffn

@deffn Command normal-mode &optional find-file
This function establishes the proper major mode and buffer-local variable
bindings for the current buffer.  First it calls @code{set-auto-mode}
(see below), then it runs @code{hack-local-variables} to parse, and
bind or evaluate as appropriate, the file's local variables
(@pxref{File 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 calling
it.  In this case, it may process local variables in the @samp{-*-}
line or at the end of the file.  The variable
@code{enable-local-variables} controls whether to do so.  @xref{File
Variables, , Local Variables in Files, emacs, The GNU Emacs Manual},
for the 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 file local variables.

If @code{normal-mode} processes the local variables list and this list
specifies a major mode, that mode overrides any mode chosen by
@code{set-auto-mode}.  If neither @code{set-auto-mode} nor
@code{hack-local-variables} specify a major mode, the buffer stays in
562 563
the major mode determined by the default value of @code{major-mode}
(see below).
Glenn Morris's avatar
Glenn Morris committed
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591

@cindex file mode specification error
@code{normal-mode} uses @code{condition-case} around the call to the
major mode function, so errors are caught and reported as a @samp{File
mode specification error},  followed by the original error message.
@end deffn

@defun set-auto-mode &optional keep-mode-if-same
@cindex visited file mode
  This function selects the major mode that is appropriate for the
current buffer.  It bases its decision (in order of precedence) on
the @w{@samp{-*-}} line, on the @w{@samp{#!}} line (using
@code{interpreter-mode-alist}), on the text at the beginning of the
buffer (using @code{magic-mode-alist}), and finally on the visited
file name (using @code{auto-mode-alist}).  @xref{Choosing Modes, , How
Major Modes are Chosen, emacs, The GNU Emacs Manual}.  However, this
function does not look for the @samp{mode:} local variable near the
end of a file; the @code{hack-local-variables} function does that.
If @code{enable-local-variables} is @code{nil}, @code{set-auto-mode}
does not check the @w{@samp{-*-}} line for a mode tag either.

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

592 593 594 595 596
@defopt major-mode
The buffer-local value of this variable holds the major mode
currently active.  The default value of this variable holds the
default major mode for new buffers.  The standard default value is
@code{fundamental-mode}.
Glenn Morris's avatar
Glenn Morris committed
597

598
If the default value of @code{major-mode} is @code{nil}, Emacs uses
Glenn Morris's avatar
Glenn Morris committed
599 600 601 602 603 604 605 606 607
the (previously) current buffer's major mode as the default major mode
of a new buffer.  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 are
those such as Dired and Rmail that are useful only with text that has
been specially prepared.
@end defopt

@defun set-buffer-major-mode buffer
608 609
This function sets the major mode of @var{buffer} to the default value of
@code{major-mode}; if that is @code{nil}, it uses the
Glenn Morris's avatar
Glenn Morris committed
610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698
current buffer's major mode (if that is suitable).  As an exception,
if @var{buffer}'s name is @samp{*scratch*}, it sets the mode to
@code{initial-major-mode}.

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

@defopt 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 major
mode command.  The default value is @code{lisp-interaction-mode}.
@end defopt

@defvar interpreter-mode-alist
This variable specifies major modes to use for scripts that specify a
command interpreter in a @samp{#!} line.  Its value is an alist with
elements of the form @code{(@var{interpreter} . @var{mode})}; for
example, @code{("perl" . perl-mode)} is one element present by
default.  The element says to use mode @var{mode} if the file
specifies an interpreter which matches @var{interpreter}.
@end defvar

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

@defvar magic-fallback-mode-alist
This works like @code{magic-mode-alist}, except that it is handled
only if @code{auto-mode-alist} does not specify a mode for this file.
@end defvar

@defvar auto-mode-alist
This variable contains an association list of file name patterns
(regular expressions) and corresponding major mode commands.  Usually,
the file name patterns test for suffixes, such as @samp{.el} and
@samp{.c}, but this need not be the case.  An ordinary 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 smallexample

When you visit a file whose expanded file name (@pxref{File Name
Expansion}), with version numbers and backup suffixes removed using
@code{file-name-sans-versions} (@pxref{File Name Components}), matches
a @var{regexp}, @code{set-auto-mode} calls the corresponding
@var{mode-function}.  This feature enables Emacs to select the 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 file
name that did not match before.  This feature is useful for
uncompression packages: an entry of the form @code{("\\.gz\\'"
@var{function} t)} can uncompress the file and then put the uncompressed
file 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 your
init 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.}
Chong Yidong's avatar
Chong Yidong committed
699
     ("/[^\\./]*\\'" . fundamental-mode)
Glenn Morris's avatar
Glenn Morris committed
700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743
     ;; @r{File name ends in @samp{.C}.}
     ("\\.C\\'" . c++-mode))
   auto-mode-alist))
@end group
@end smallexample
@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 information
about 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-mode
This 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, it
displays the documentation string of the major mode function.
(@xref{Accessing Documentation}.)
@end deffn

@defvar major-mode
This buffer-local variable holds the symbol for the current buffer's
major mode.  This symbol should have a function definition that is the
command to switch to that major mode.  The @code{describe-mode}
function uses the documentation string of the function as the
documentation of the major mode.
@end defvar

@node Derived Modes
@subsection Defining Derived Modes
@cindex derived mode

  It's often useful to define a new major mode in terms of an existing
one.  An easy way to do this is to use @code{define-derived-mode}.

@defmac define-derived-mode variant parent name docstring keyword-args@dots{} body@dots{}
744
This macro defines @var{variant} as a major mode command, using
Glenn Morris's avatar
Glenn Morris committed
745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781
@var{name} as the string form of the mode name.  @var{variant} and
@var{parent} should be unquoted symbols.

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

@itemize @bullet
@item
The new mode has its own sparse keymap, named
@code{@var{variant}-map}.  @code{define-derived-mode}
makes the parent mode's keymap the parent of the new map, unless
@code{@var{variant}-map} is already set and already has a parent.

@item
The new mode has its own syntax table, kept in the variable
@code{@var{variant}-syntax-table}, unless you override this using the
@code{:syntax-table} keyword (see below).  @code{define-derived-mode}
makes the parent mode's syntax-table the parent of
@code{@var{variant}-syntax-table}, unless the latter is already set
and already has a parent different from the standard syntax table.

@item
The new mode has its own abbrev table, kept in the variable
@code{@var{variant}-abbrev-table}, unless you override this using the
@code{:abbrev-table} keyword (see below).

@item
The new mode has its own mode hook, @code{@var{variant}-hook}.  It
runs this hook, after running the hooks of its ancestor modes, with
@code{run-mode-hooks}, as the last thing it does. @xref{Mode Hooks}.
@end itemize

In 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 usual
overrides, just before running the mode hooks.

782 783 784 785 786 787
If @var{parent} has a non-@code{nil} @code{mode-class} symbol
property, then @code{define-derived-mode} sets the @code{mode-class}
property of @var{variant} to the same value.  This ensures, for
example, that if @var{parent} is a special mode, then @var{variant} is
also a special mode (@pxref{Major Mode Conventions}).

Glenn Morris's avatar
Glenn Morris committed
788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064
You can also specify @code{nil} for @var{parent}.  This gives the new
mode no parent.  Then @code{define-derived-mode} behaves as described
above, but, of course, omits all actions connected with @var{parent}.

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

The @var{keyword-args} are pairs of keywords and values.  The values
are evaluated.  The following keywords are currently supported:

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

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

@item :group
If this is specified, the value should be the customization group for
this mode.  (Not all major modes have one.)  Only the (still
experimental and unadvertised) command @code{customize-mode} currently
uses this.  @code{define-derived-mode} does @emph{not} automatically
define the specified customization group.
@end table

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 example

Do not write an @code{interactive} spec in the definition;
@code{define-derived-mode} does that automatically.
@end defmac

@node Generic Modes
@subsection Generic Modes
@cindex generic mode

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

@defmac define-generic-mode mode comment-list keyword-list font-lock-list auto-mode-list function-list &optional docstring
This macro defines a generic mode command named @var{mode} (a symbol,
not quoted).  The optional argument @var{docstring} is the
documentation for the mode command.  If you do not supply it,
@code{define-generic-mode} generates one by default.

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

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

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

Finally, @var{function-list} is a list of functions for the mode
command to call for additional setup.  It calls these functions just
before it runs the mode hook variable @code{@var{mode}-hook}.
@end defmac

@node Mode Hooks
@subsection Mode Hooks

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

  Emacs versions before Emacs 22 did not have @code{delay-mode-hooks}.
When user-implemented major modes have not been updated to use it,
they won't entirely follow these conventions: they may run the
parent's mode hook too early, or fail to run
@code{after-change-major-mode-hook}.  If you encounter such a major
mode, please correct it to follow these conventions.

  When you defined a major mode using @code{define-derived-mode}, it
automatically makes sure these conventions are followed.  If you
define a major mode ``by hand,'' not using @code{define-derived-mode},
use the following functions to handle these conventions automatically.

@defun run-mode-hooks &rest hookvars
Major modes should run their mode hook using this function.  It is
similar to @code{run-hooks} (@pxref{Hooks}), but it also runs
@code{after-change-major-mode-hook}.

When this function is called during the execution of a
@code{delay-mode-hooks} form, it does not run the hooks immediately.
Instead, it arranges for the next call to @code{run-mode-hooks} to run
them.
@end defun

@defmac delay-mode-hooks body@dots{}
When one major mode command calls another, it should do so inside of
@code{delay-mode-hooks}.

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

@defvar after-change-major-mode-hook
This is a normal hook run by @code{run-mode-hooks}.  It is run at the
very end of every properly-written major mode function.
@end defvar

@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 of
the conventions listed above:

@smallexample
@group
;; @r{Create the syntax table for this mode.}
(defvar text-mode-syntax-table
  (let ((st (make-syntax-table)))
    (modify-syntax-entry ?\" ".   " st)
    (modify-syntax-entry ?\\ ".   " st)
    ;; Add `p' so M-c on `hello' leads to `Hello', not `hello'.
    (modify-syntax-entry ?' "w p" st)
    st)
  "Syntax table used while in `text-mode'.")
@end group

;; @r{Create the keymap for this mode.}
@group
(defvar text-mode-map
  (let ((map (make-sparse-keymap)))
    (define-key map "\e\t" 'ispell-complete-word)
    (define-key map "\es" 'center-line)
    (define-key map "\eS" 'center-paragraph)
    map)
  "Keymap for `text-mode'.
Many other modes, such as Mail mode, Outline mode
and Indented Text mode, inherit all the commands
defined in this map.")
@end group
@end smallexample

  Here is how the actual mode command is defined now:

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

@noindent
(The last line is redundant nowadays, since @code{indent-relative} is
the default value, and we'll delete it in a future version.)

  Here is how it was defined formerly, before
@code{define-derived-mode} existed:

@smallexample
@group
;; @r{This isn't needed nowadays, since @code{define-derived-mode} does it.}
(defvar text-mode-abbrev-table nil
  "Abbrev table used while in text mode.")
(define-abbrev-table 'text-mode-abbrev-table ())
@end group

@group
(defun text-mode ()
  "Major mode for editing text intended for humans to read...
 Special commands: \\@{text-mode-map@}
@end group
@group
Turning 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
  ;; @r{These four lines are absent from the current version}
  ;; @r{not because this is done some other way, but rather}
  ;; @r{because nowadays Text mode uses the normal definition of paragraphs.}
  (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 Lisp
Interaction mode) have more features than Text mode and the code is
correspondingly 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 lisp-mode-abbrev-table nil "")
@end group

@group
(defvar emacs-lisp-mode-syntax-table
  (let ((table (make-syntax-table)))
    (let ((i 0))
@end group

@group
      ;; @r{Set syntax of chars up to @samp{0} to say they are}
      ;;   @r{part of symbol names but not words.}
      ;;   @r{(The digit @samp{0} is @code{48} in the @acronym{ASCII} character set.)}
      (while (< i ?0)
1065 1066
        (modify-syntax-entry i "_   " table)
        (setq i (1+ i)))
Glenn Morris's avatar
Glenn Morris committed
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719
      ;; @r{@dots{} similar code follows for other character ranges.}
@end group
@group
      ;; @r{Then set the syntax codes for characters that are special in Lisp.}
      (modify-syntax-entry ?  "    " table)
      (modify-syntax-entry ?\t "    " table)
      (modify-syntax-entry ?\f "    " table)
      (modify-syntax-entry ?\n ">   " table)
@end group
@group
      ;; @r{Give CR the same syntax as newline, for selective-display.}
      (modify-syntax-entry ?\^m ">   " table)
      (modify-syntax-entry ?\; "<   " table)
      (modify-syntax-entry ?` "'   " table)
      (modify-syntax-entry ?' "'   " table)
      (modify-syntax-entry ?, "'   " table)
@end group
@group
      ;; @r{@dots{}likewise for many other characters@dots{}}
      (modify-syntax-entry ?\( "()  " table)
      (modify-syntax-entry ?\) ")(  " table)
      (modify-syntax-entry ?\[ "(]  " table)
      (modify-syntax-entry ?\] ")[  " table))
    table))
@end group
@group
;; @r{Create an abbrev table for lisp-mode.}
(define-abbrev-table 'lisp-mode-abbrev-table ())
@end group
@end smallexample

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

@smallexample
@group
(defun lisp-mode-variables (lisp-syntax)
  (when lisp-syntax
    (set-syntax-table lisp-mode-syntax-table))
  (setq local-abbrev-table lisp-mode-abbrev-table)
  @dots{}
@end group
@end smallexample

  In Lisp and most programming languages, we want the paragraph
commands to treat only blank lines as paragraph separators.  And the
modes should understand the Lisp conventions for comments.  The rest of
@code{lisp-mode-variables} sets this up:

@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.  For
example, Lisp mode binds @kbd{C-c C-z} to @code{run-lisp}, but the other
Lisp modes do not.  However, all Lisp modes have some commands in
common.  The following code sets up the common commands:

@smallexample
@group
(defvar shared-lisp-mode-map ()
  "Keymap for commands shared by all sorts of Lisp modes.")

;; @r{Putting this @code{if} after the @code{defvar} is an older style.}
(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

@noindent
And 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 for
Lisp 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 job
or to switch back to an existing one.
@end group

@group
Entry 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.}
  (make-local-variable 'comment-start-skip)
  (setq comment-start-skip
        "\\(\\(^\\|[^\\\\\n]\\)\\(\\\\\\\\\\)*\\)\\(;+\\|#|\\) *")
  (make-local-variable 'font-lock-keywords-case-fold-search)
  (setq font-lock-keywords-case-fold-search t)
@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 Minor Modes
@section Minor Modes
@cindex minor mode

  A @dfn{minor mode} provides features that users may enable or disable
independently of the choice of major mode.  Minor modes can be enabled
individually or in combination.  Minor modes would be better named
``generally available, optional feature modes,'' except that such a name
would 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.  For
example, Auto Fill mode works with any major mode that permits text
insertion.  To be general, a minor mode must be effectively independent
of the things major modes do.

  A minor mode is often much more difficult to implement than a major
mode.  One reason is that you should be able to activate and deactivate
minor modes in any order.  A minor mode should be able to have its
desired effect regardless of the major mode and regardless of the other
minor modes in effect.

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

@defvar minor-mode-list
The 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 for
major modes.  Several of the major mode conventions apply to minor
modes as well: those regarding the name of the mode initialization
function, the names of global symbols, the use of a hook at the end of
the initialization function, and the use of keymaps and other tables.

  In addition, there are several conventions that are specific to
minor modes.  (The easiest way to follow all the conventions is to use
the macro @code{define-minor-mode}; @ref{Defining Minor Modes}.)

@itemize @bullet
@item
@cindex mode variable
Make a variable whose name ends in @samp{-mode} to control the minor
mode.  We call this the @dfn{mode variable}.  The minor mode command
should set this variable (@code{nil} to disable; anything else to
enable).

If possible, implement the mode so that setting the variable
automatically enables or disables the mode.  Then the minor mode command
does not need to do anything except set the variable.

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

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

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

The command should accept one optional argument.  If the argument is
@code{nil}, it should toggle the mode (turn it on if it is off, and
off if it is on).  It should turn the mode on if the argument is a
positive integer, the symbol @code{t}, or a list whose @sc{car} is one
of those.  It should turn the mode off if the argument is a negative
integer or zero, the symbol @code{-}, or a list whose @sc{car} is a
negative integer or zero.  The meaning of other arguments is not
specified.

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 or
disables 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

@item
Add an element to @code{minor-mode-alist} for each minor mode
(@pxref{Definition of minor-mode-alist}), if you want to indicate the
minor mode in the mode line.  This element should be a list of the
following form:

@smallexample
(@var{mode-variable} @var{string})
@end smallexample

Here @var{mode-variable} is the variable that controls enabling of the
minor 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 so
that there is room for several of them at once.

When you add an element to @code{minor-mode-alist}, use @code{assq} to
check 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

@noindent
or like this, using @code{add-to-list} (@pxref{List 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 support
enabling and disabling via Custom (@pxref{Customization}).  To do this,
the first step is to define the mode variable with @code{defcustom}, and
specify @code{:type boolean}.

  If just setting the variable is not sufficient to enable the mode, you
should also specify a @code{:set} method which enables the mode by
invoking the mode command.  Note in the variable's documentation string that
setting the variable other than via Custom may not take effect.

  Also mark the definition with an autoload cookie (@pxref{autoload cookie}),
and specify a @code{:require} so that customizing the variable will load
the library that defines the mode.  This will copy suitable definitions
into @file{loaddefs.el} so that users can use @code{customize-option} to
enable 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 'custom-set-minor-mode
  :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 mode
is enabled.  To set up a keymap for a minor mode, add an element to the
alist @code{minor-mode-map-alist}.  @xref{Definition of minor-mode-map-alist}.

@cindex @code{self-insert-command}, minor modes
  One use of minor mode keymaps is to modify the behavior of certain
self-inserting characters so that they do something else as well as
self-insert.  In general, this is the only way to do that, since the
facilities for customizing @code{self-insert-command} are limited to
special cases (designed for abbrevs and Auto Fill mode).  (Do not try
substituting your own definition of @code{self-insert-command} for the
standard 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 one of @kbd{.,/?`'"[]\|~!#$%^&*()-_+=}.  (The other
punctuation characters are reserved for major modes.)

@node Defining Minor Modes
@subsection Defining Minor Modes

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

@defmac define-minor-mode mode doc [init-value [lighter [keymap]]] keyword-args@dots{} body@dots{}
This macro defines a new minor mode whose name is @var{mode} (a
symbol).  It defines a command named @var{mode} to toggle the minor
mode, with @var{doc} as its documentation string.  It also defines a
variable named @var{mode}, which is set to @code{t} or @code{nil} by
enabling or disabling the mode.  The variable is initialized to
@var{init-value}.  Except in unusual circumstances (see below), this
value must be @code{nil}.

The string @var{lighter} says what to display in the mode line
when the mode is enabled; if it is @code{nil}, the mode is not displayed
in 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 alist
specifying bindings in this form:

@example
(@var{key-sequence} . @var{definition})
@end example

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

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

@item :global @var{global}
If non-@code{nil}, this specifies that the minor mode should be global
rather than buffer-local.  It defaults to @code{nil}.

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

@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 table

Any other keyword arguments are passed directly to the
@code{defcustom} generated for the variable @var{mode}.

The command named @var{mode} first performs the standard actions such
as setting the variable named @var{mode} and then executes the
@var{body} forms, if any.  It finishes by running the mode hook
variable @code{@var{mode}-hook}.
@end defmac

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

@findex easy-mmode-define-minor-mode
  The name @code{easy-mmode-define-minor-mode} is an alias
for 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 key
gobbles all preceding whitespace except the last.
See the command \\[hungry-electric-delete]."
 ;; The initial value.
 nil
 ;; The indicator for the mode line.
 " Hungry"
 ;; The minor mode bindings.
 '(("\C-\^?" . hungry-electric-delete))
 :group 'hunger)
@end smallexample

@noindent
This 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 the
mode is enabled.  It initializes the keymap with a key binding for
@kbd{C-@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 key
gobbles all preceding whitespace except the last.
See the command \\[hungry-electric-delete]."
 ;; The initial value.
 :init-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

@defmac define-globalized-minor-mode global-mode mode turn-on keyword-args@dots{}
This defines a global toggle named @var{global-mode} whose meaning is
to enable or disable the buffer-local minor mode @var{mode} in all
buffers.  To turn on the minor mode in a buffer, it uses the function
@var{turn-on}; to turn off the minor mode, it calls @code{mode} with
@minus{}1 as argument.

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

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

Use @code{:group @var{group}} in @var{keyword-args} to specify the
custom group for the mode variable of the global minor mode.
@end defmac

@node Mode Line Format
@section Mode-Line Format
@cindex mode line

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

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

@menu
* Base: Mode Line Basics. Basic ideas of mode line control.
* Data: Mode Line Data.   The data structure that controls the mode line.
* Top: Mode Line Top.     The top level variable, mode-line-format.
* 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 Basics
@subsection Mode Line Basics

  @code{mode-line-format} is a buffer-local variable that holds a
@dfn{mode line construct}, a kind of template, which controls what is
displayed on the mode line of the current buffer.  The value of
@code{header-line-format} specifies the buffer's header line in the
same way.  All windows for the same buffer use the same
@code{mode-line-format} and @code{header-line-format}.

  For efficiency, Emacs does not continuously recompute the mode
line and header line of a window.  It does so when circumstances
appear to call for it---for instance, if you change the window
configuration, switch buffers, narrow or widen the buffer, scroll, or
change the buffer's modification status.  If you modify any of the
variables referenced by @code{mode-line-format} (@pxref{Mode Line
Variables}), or any other variables and data structures that affect
how text is displayed (@pxref{Display}), you may want to force an
update of the mode line so as to display the new information or
display it in the new way.

@defun force-mode-line-update &optional all
Force redisplay of the current buffer's mode line and header line.
The next redisplay will update the mode line and header line based on
the latest values of all relevant variables.  With optional
non-@code{nil} @var{all}, force redisplay of all mode lines and header
lines.

This function also forces recomputation of the menu bar menus
and the frame title.
@end defun

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

@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 called a
@dfn{mode-line construct}, made up of lists, strings, symbols, and
numbers kept in buffer-local variables.  Each data type has a specific
meaning for the mode-line appearance, as described below.  The same
data structure is used for constructing frame titles (@pxref{Frame
Titles}) and header lines (@pxref{Header Lines}).

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

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

@table @code
@cindex percent symbol in mode line
@item @var{string}
A string as a mode-line construct appears verbatim except for
@dfn{@code{%}-constructs} in it.  These stand for substitution of
other data; see @ref{%-Constructs}.

If parts of the string have @code{face} properties, they control
display of the text just as they would text in the buffer.  Any
characters which have no @code{face} properties are displayed, by
default, in the face @code{mode-line} or @code{mode-line-inactive}
(@pxref{Standard Faces,,, emacs, The GNU Emacs Manual}).  The
@code{help-echo} and @code{local-map} properties in @var{string} have
special meanings.  @xref{Properties in Mode}.

@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 any
symbol whose value is void.

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

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

@item (@var{string} @var{rest}@dots{})
@itemx (@var{list} @var{rest}@dots{})
A list whose first element is a string or list means to process all the
elements recursively and concatenate the results.  This is the most
common form of mode-line construct.

@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.  Make sure this
evaluation cannot load any files, as doing so could cause infinite
recursion.

@item (:propertize @var{elt} @var{props}@dots{})
A list whose first element is the symbol @code{:propertize} says to
process the mode-line construct @var{elt} recursively, then add the text
properties 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 22.1.)

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

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

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

@node Mode Line Top
@subsection The Top Level of Mode Line Control

  The variable in overall control of the mode line is
@code{mode-line-format}.

1720
@defopt mode-line-format
Glenn Morris's avatar
Glenn Morris committed
1721 1722 1723 1724 1725 1726
The value of this variable is a mode-line construct that controls the
contents of the mode-line.  It is always buffer-local in all buffers.

If you set this variable to @code{nil} in a buffer, that buffer does
not have a mode line.  (A window that is just one line tall never
displays a mode line.)
1727
@end defopt
Glenn Morris's avatar
Glenn Morris committed
1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805

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

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

  Here is an example of a @code{mode-line-format} that might be
useful for @code{shell-mode}, since it contains the host name and default
directory.

@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 the standard value
of @code{mode-line-format} into the text of the mode line.  There is
nothing inherently special about these variables; any other variables
could have the same effects on the mode line if
@code{mode-line-format}'s value were changed to use them.  However,
various parts of Emacs set these variables on the understanding that
they will control parts of the mode line; therefore, practically
speaking, it is essential for the mode line to use them.

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

@defvar mode-line-modified
This variable holds the value of the mode-line construct that displays
1806 1807 1808 1809
whether the current buffer is modified.  Its default value displays
@samp{**} if the buffer is modified, @samp{--} if the buffer is not
modified, @samp{%%} if the buffer is read only, and @samp{%*} if the
buffer is read only and modified.
Glenn Morris's avatar
Glenn Morris committed
1810 1811 1812 1813 1814

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

@defvar mode-line-frame-identification
1815 1816 1817 1818
This variable identifies the current frame.  Its default value
displays @code{" "} if you are using a window system which can show
multiple frames, or @code{"-%F "} on an ordinary terminal which shows
only one frame at a time.
Glenn Morris's avatar
Glenn Morris committed
1819 1820 1821
@end defvar

@defvar mode-line-buffer-identification
1822 1823 1824
This variable identifies the buffer being displayed in the window.
Its default value displays the buffer name, padded with spaces to at
least 12 columns.
Glenn Morris's avatar
Glenn Morris committed
1825 1826
@end defvar

1827
@defopt mode-line-position
1828 1829 1830
This variable indicates the position in the buffer.  Its default value
displays the buffer percentage and, optionally, the buffer size, the
line number and the column number.
1831
@end defopt
Glenn Morris's avatar
Glenn Morris committed
1832 1833 1834 1835 1836 1837 1838 1839

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

1840
@defopt mode-line-modes
1841 1842 1843
This variable displays the buffer's major and minor modes.  Its
default value also displays the recursive editing level, information
on the process status, and whether narrowing is in effect.
1844
@end defopt
Glenn Morris's avatar
Glenn Morris committed
1845 1846 1847 1848 1849

  The following three variables are used in @code{mode-line-modes}:

@defvar mode-name
This buffer-local variable holds the ``pretty'' name of the current
1850 1851 1852 1853 1854 1855
buffer's major mode.  Each major mode should set this variable so that
the mode name will appear in the mode line.  The value does not have
to be a string, but can use any of the data types valid in a mode-line
construct (@pxref{Mode Line Data}).  To compute the string that will
identify the mode name in the mode line, use @code{format-mode-line}
(@pxref{Emulating Mode Line}).
Glenn Morris's avatar
Glenn Morris committed
1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903
@end defvar

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

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

@example
(@var{minor-mode-variable} @var{mode-line-string})
@end example

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

@code{minor-mode-alist} itself is not buffer-local.  Each variable
mentioned in the alist should be buffer-local if its minor mode can be
enabled separately in each buffer.
@end defvar

@defvar global-mode-string
This variable holds a mode-line spec that, by default, appears in the
mode 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 time
and load information.

The @samp{%M} construct substitutes the value of
@code{global-mode-string}, but that is obsolete, since the variable is
included in the mode line from @code{mode-line-format}.
@end defvar

Here is a simplified version of the default value of
1904
@code{mode-line-format}.  The real default value also
Glenn Morris's avatar
Glenn Morris committed
1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396
specifies 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

@node %-Constructs
@subsection @code{%}-Constructs in the Mode Line

  Strings used as mode-line constructs can use certain
@code{%}-constructs to substitute various kinds of data.  Here is a
list of the defined @code{%}-constructs, and what they mean.  In any
construct except @samp{%%}, you can add a decimal integer after the
@samp{%} to specify a minimum field width.  If the width is less, the
field is padded with spaces to the right.

@table @code
@item %b
The current buffer name, obtained with the @code{buffer-name} function.
@xref{Buffer Names}.

@item %c
The current column number of point.

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

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

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

@item %i
The size of the accessible part of the current buffer; basically
@code{(- (point-max) (point-min))}.

@item %I
Like @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., to
abbreviate.

@item %l
The current line number of point, counting within the accessible portion
of the buffer.

@item %n
@samp{Narrow} when narrowing is in effect; nothing otherwise (see
@code{narrow-to-region} in @ref{Narrowing}).

@item %p
The percentage of the buffer text above the @strong{top} of window, or
@samp{Top}, @samp{Bottom} or @samp{All}.  Note that the default
mode-line specification truncates this to three characters.

@item %P
The percentage of the buffer text that is above the @strong{bottom} of
the window (which includes the text visible in the window, as well as
the text above the top), plus @samp{Top} if the top of the buffer is
visible on screen; or @samp{Bottom} or @samp{All}.

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

@item %t
Whether the visited file is a text file or a binary file.  This is a
meaningful distinction only on certain operating systems (@pxref{MS-DOS
File Types}).

@item %z
The mnemonics of keyboard, terminal, and buffer coding systems.

@item %Z
Like @samp{%z}, but including the end-of-line format.

@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 modified
read-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 counting
minibuffer levels): one @samp{[} for each editing level.
@xref{Recursive Editing}.

@item %]
One @samp{]} for each recursive editing level (not counting minibuffer
levels).

@item %-
Dashes sufficient to fill the remainder of the mode line.

@item %%
The character @samp{%}---this is how to include a literal @samp{%} in a
string in which @code{%}-constructs are allowed.
@end table

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

@table @code
@item %m
The value of @code{mode-name}.

@item %M
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

  Certain text properties are meaningful in the
mode line.  The @code{face} property affects the appearance of text; the
@code{help-echo} property associates 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 mode
line:

@enumerate
@item
Put a string with a text property directly into the mode-line data
structure.

@item
Put a text property on a mode-line %-construct such as @samp{%12b}; then
the expansion of the %-construct will have that same text property.

@item
Use a @code{(:propertize @var{elt} @var{props}@dots{})} construct to
give @var{elt} a text property specified by @var{props}.

@item
Use a list containing @code{:eval @var{form}} in the mode-line data
structure, and make @var{form} evaluate to a string that has a text
property.
@end enumerate

  You can use the @code{local-map} property to specify a keymap.  This
keymap only takes real effect for mouse clicks; binding character keys
and function keys to it has no effect,