aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorRichard M. Stallman1994-03-21 07:49:21 +0000
committerRichard M. Stallman1994-03-21 07:49:21 +0000
commita44af9f249228b7ef191d809b5d0d385489bb38a (patch)
treec631547f74ef2319ff64149ff35bcc249fb25e7b
parent14423a05388f5b18c65012213e2ed5015b73fbc1 (diff)
downloademacs-a44af9f249228b7ef191d809b5d0d385489bb38a.tar.gz
emacs-a44af9f249228b7ef191d809b5d0d385489bb38a.zip
Initial revision
-rw-r--r--lispref/elisp.texi903
-rw-r--r--lispref/internals.texi807
-rw-r--r--lispref/maps.texi133
-rw-r--r--lispref/modes.texi1364
4 files changed, 3207 insertions, 0 deletions
diff --git a/lispref/elisp.texi b/lispref/elisp.texi
new file mode 100644
index 00000000000..3b54cb66444
--- /dev/null
+++ b/lispref/elisp.texi
@@ -0,0 +1,903 @@
1\input texinfo @c -*-texinfo-*-
2@c %**start of header
3@setfilename elisp
4@smallbook
5@settitle GNU Emacs Lisp Reference Manual
6@c %**end of header
7
8@ifinfo
9This version is the edition 2.3 of the GNU Emacs Lisp
10Reference Manual. It corresponds to Emacs Version 19.23.
11@c Please REMEMBER to update edition number in *four* places in this file
12@c and also in *one* place in intro.texi
13
14Published by the Free Software Foundation
15675 Massachusetts Avenue
16Cambridge, MA 02139 USA
17
18Copyright (C) 1990, 1991, 1992, 1993, 1994 Free Software Foundation, Inc.
19
20Permission is granted to make and distribute verbatim copies of this
21manual provided the copyright notice and this permission notice are
22preserved on all copies.
23
24@ignore
25Permission is granted to process this file through TeX and print the
26results, provided the printed document carries copying permission notice
27identical to this one except for the removal of this paragraph (this
28paragraph not being relevant to the printed manual).
29
30@end ignore
31Permission is granted to copy and distribute modified versions of this
32manual under the conditions for verbatim copying, provided that the
33entire resulting derived work is distributed under the terms of a
34permission notice identical to this one.
35
36Permission is granted to copy and distribute translations of this manual
37into another language, under the above conditions for modified versions,
38except that this permission notice may be stated in a translation
39approved by the Foundation.
40
41Permission is granted to copy and distribute modified versions of this
42manual under the conditions for verbatim copying, provided also that the
43section entitled ``GNU General Public License'' is included exactly as
44in the original, and provided that the entire resulting derived work is
45distributed under the terms of a permission notice identical to this
46one.
47
48Permission is granted to copy and distribute translations of this manual
49into another language, under the above conditions for modified versions,
50except that the section entitled ``GNU General Public License'' may be
51included in a translation approved by the Free Software Foundation
52instead of in the original English.
53@end ifinfo
54
55@c Combine indices.
56@synindex cp fn
57@syncodeindex vr fn
58@syncodeindex ky fn
59@syncodeindex pg fn
60@syncodeindex tp fn
61
62@setchapternewpage odd
63@finalout
64
65@titlepage
66@title GNU Emacs Lisp Reference Manual
67@subtitle GNU Emacs Version 19
68@subtitle for Unix Users
69@c The edition number appears in several places in this file
70@c and also in the file intro.texi.
71@subtitle Second Edition, June 1993
72@subtitle Revision 2.3, April 1994
73
74@author by Bil Lewis, Dan LaLiberte, Richard Stallman
75@author and the GNU Manual Group
76@page
77@vskip 0pt plus 1filll
78Copyright @copyright{} 1990, 1991, 1992, 1993, 1994 Free Software Foundation, Inc.
79
80@sp 2
81Second Edition @*
82Revised for Emacs Version 19.23,@*
83April 1994.@*
84@sp 2
85ISBN 1-882114-40-X
86
87@sp 2
88Published by the Free Software Foundation @*
89675 Massachusetts Avenue @*
90Cambridge, MA 02139 USA
91
92Permission is granted to make and distribute verbatim copies of this
93manual provided the copyright notice and this permission notice are
94preserved on all copies.
95
96Permission is granted to copy and distribute modified versions of this
97manual under the conditions for verbatim copying, provided also that the
98section entitled ``GNU General Public License'' is included
99exactly as in the original, and provided that the entire resulting
100derived work is distributed under the terms of a permission notice
101identical to this one.
102
103Permission is granted to copy and distribute translations of this manual
104into another language, under the above conditions for modified versions,
105except that the section entitled ``GNU General Public License'' may be
106included in a translation approved by the Free Software Foundation
107instead of in the original English.
108
109Cover art by Etienne Suvasa.
110@end titlepage
111@page
112
113@node Top, Copying, (dir), (dir)
114
115@ifinfo
116This Info file contains edition 2.3 of the GNU Emacs Lisp
117Reference Manual, corresponding to GNU Emacs version 19.23.
118@end ifinfo
119
120@menu
121* Copying:: Conditions for copying and changing GNU Emacs.
122* Introduction:: Introduction and conventions used.
123
124* Types of Lisp Object:: Data types in Emacs Lisp.
125* Numbers:: Numbers and arithmetic functions.
126* Strings and Characters:: Strings, and functions that work on them.
127* Lists:: Lists, cons cells, and related functions.
128* Sequences Arrays Vectors:: Lists, strings and vectors are called sequences.
129 Certain functions act on any kind of sequence.
130 The description of vectors is here as well.
131* Symbols:: Symbols represent names, uniquely.
132
133* Evaluation:: How Lisp expressions are evaluated.
134* Control Structures:: Conditionals, loops, nonlocal exits.
135* Variables:: Using symbols in programs to stand for values.
136* Functions:: A function is a Lisp program
137 that can be invoked from other functions.
138* Macros:: Macros are a way to extend the Lisp language.
139
140* Loading:: Reading files of Lisp code into Lisp.
141* Byte Compilation:: Compilation makes programs run faster.
142* Debugging:: Tools and tips for debugging Lisp programs.
143
144* Streams:: Converting Lisp objects to text and back.
145* Minibuffers:: Using the minibuffer to read input.
146* Command Loop:: How the editor command loop works,
147 and how you can call its subroutines.
148* Keymaps:: Defining the bindings from keys to commands.
149* Modes:: Defining major and minor modes.
150* Documentation:: Writing and using documentation strings.
151
152* Files:: Accessing files.
153* Backups and Auto-Saving:: Controlling how backups and auto-save
154 files are made.
155* Buffers:: Creating and using buffer objects.
156* Windows:: Manipulating windows and displaying buffers.
157* Frames:: Making multiple X windows.
158* Positions:: Buffer positions and motion functions.
159* Markers:: Markers represent positions and update
160 automatically when the text is changed.
161
162* Text:: Examining and changing text in buffers.
163* Searching and Matching:: Searching buffers for strings or regexps.
164* Syntax Tables:: The syntax table controls word and list parsing.
165* Abbrevs:: How Abbrev mode works, and its data structures.
166
167* Processes:: Running and communicating with subprocesses.
168* System Interface:: Getting the user id, system type, environment
169 variables, and other such things.
170* Display:: Parameters controlling screen usage.
171 The bell. Waiting for input.
172* Calendar:: Customizing the calendar and diary.
173
174Appendices
175
176* Tips:: Advice for writing Lisp programs.
177* GNU Emacs Internals:: Building and dumping Emacs;
178 internal data structures.
179* Standard Errors:: List of all error symbols.
180* Standard Buffer-Local Variables:: List of variables local in all buffers.
181* Standard Keymaps:: List of standard keymaps.
182* Standard Hooks:: List of standard hook variables.
183
184* Antinews:: Information about Emacs 18.
185
186* Index:: Index including concepts, functions, variables,
187 and other terms.
188
189 --- The Detailed Node Listing ---
190
191Here are other nodes that are inferiors of those already listed,
192mentioned here so you can get to them in one step:
193
194Introduction
195
196* Caveats:: Flaws and a request for help.
197* Lisp History:: Emacs Lisp is descended from Maclisp.
198* Conventions:: How the manual is formatted.
199* Acknowledgements:: The authors, editors, and sponsors of this manual.
200
201Conventions
202
203* Some Terms:: Explanation of terms we use in this manual.
204* nil and t:: How the symbols @code{nil} and @code{t} are used.
205* Evaluation Notation:: The format we use for examples of evaluation.
206* Printing Notation:: The format we use for examples that print output.
207* Error Messages:: The format we use for examples of errors.
208* Buffer Text Notation:: The format we use for buffer contents in examples.
209* Format of Descriptions:: Notation for describing functions, variables, etc.
210
211Format of Descriptions
212
213* A Sample Function Description::
214* A Sample Variable Description::
215
216Lisp Data Types
217
218* Printed Representation:: How Lisp objects are represented as text.
219* Comments:: Comments and their formatting conventions.
220* Programming Types:: Types found in all Lisp systems.
221* Editing Types:: Types specific to Emacs.
222* Type Predicates:: Tests related to types.
223* Equality Predicates:: Tests of equality between any two objects.
224
225Programming Types
226
227* Integer Type:: Numbers without fractional parts.
228* Floating Point Type:: Numbers with fractional parts and with a large range.
229* Character Type:: The representation of letters, numbers and
230 control characters.
231* Sequence Type:: Both lists and arrays are classified as sequences.
232* List Type:: Lists gave Lisp its name (not to mention reputation).
233* Array Type:: Arrays include strings and vectors.
234* String Type:: An (efficient) array of characters.
235* Vector Type:: One-dimensional arrays.
236* Symbol Type:: A multi-use object that refers to a function,
237 variable, property list, or itself.
238* Lisp Function Type:: A piece of executable code you can call from elsewhere.
239* Lisp Macro Type:: A method of expanding an expression into another
240 expression, more fundamental but less pretty.
241* Primitive Function Type:: A function written in C, callable from Lisp.
242* Byte-Code Type:: A function written in Lisp, then compiled.
243* Autoload Type:: A type used for automatically loading seldom-used
244 functions.
245
246List Type
247
248* Dotted Pair Notation:: An alternative syntax for lists.
249* Association List Type:: A specially constructed list.
250
251Editing Types
252
253* Buffer Type:: The basic object of editing.
254* Window Type:: What makes buffers visible.
255* Window Configuration Type::Save what the screen looks like.
256* Marker Type:: A position in a buffer.
257* Process Type:: A process running on the underlying OS.
258* Stream Type:: Receive or send characters.
259* Keymap Type:: What function a keystroke invokes.
260* Syntax Table Type:: What a character means.
261
262Numbers
263
264* Integer Basics:: Representation and range of integers.
265* Float Basics:: Representation and range of floating point.
266* Predicates on Numbers:: Testing for numbers.
267* Comparison of Numbers:: Equality and inequality predicates.
268* Arithmetic Operations:: How to add, subtract, multiply and divide.
269* Bitwise Operations:: Logical and, or, not, shifting.
270* Numeric Conversions:: Converting float to integer and vice versa.
271* Transcendental Functions:: Trig, exponential and logarithmic functions.
272* Random Numbers:: Obtaining random integers, predictable or not.
273
274Strings and Characters
275
276* String Basics:: Basic properties of strings and characters.
277* Predicates for Strings:: Testing whether an object is a string or char.
278* Creating Strings:: Functions to allocate new strings.
279* Text Comparison:: Comparing characters or strings.
280* String Conversion:: Converting characters or strings and vice versa.
281* Formatting Strings:: @code{format}: Emacs's analog of @code{printf}.
282* Character Case:: Case conversion functions.
283
284Lists
285
286* Cons Cells:: How lists are made out of cons cells.
287* Lists as Boxes:: Graphical notation to explain lists.
288* List-related Predicates:: Is this object a list? Comparing two lists.
289* List Elements:: Extracting the pieces of a list.
290* Building Lists:: Creating list structure.
291* Modifying Lists:: Storing new pieces into an existing list.
292* Sets And Lists:: A list can represent a finite mathematical set.
293* Association Lists:: A list can represent a finite relation or mapping.
294
295Modifying Existing List Structure
296
297* Setcar:: Replacing an element in a list.
298* Setcdr:: Replacing part of the list backbone.
299 This can be used to remove or add elements.
300* Rearrangement:: Reordering the elements in a list; combining lists.
301
302Sequences, Arrays, and Vectors
303
304* Sequence Functions:: Functions that accept any kind of sequence.
305* Arrays:: Characteristics of arrays in Emacs Lisp.
306* Array Functions:: Functions specifically for arrays.
307* Vectors:: Functions specifically for vectors.
308
309Symbols
310
311* Symbol Components:: Symbols have names, values, function definitions
312 and property lists.
313* Definitions:: A definition says how a symbol will be used.
314* Creating Symbols:: How symbols are kept unique.
315* Property Lists:: Each symbol has a property list
316 for recording miscellaneous information.
317
318Evaluation
319
320* Intro Eval:: Evaluation in the scheme of things.
321* Eval:: How to invoke the Lisp interpreter explicitly.
322* Forms:: How various sorts of objects are evaluated.
323* Quoting:: Avoiding evaluation (to put constants in
324 the program).
325
326Kinds of Forms
327
328* Self-Evaluating Forms:: Forms that evaluate to themselves.
329* Symbol Forms:: Symbols evaluate as variables.
330* Classifying Lists:: How to distinguish various sorts of list forms.
331* Function Forms:: Forms that call functions.
332* Macro Forms:: Forms that call macros.
333* Special Forms:: ``Special forms'' are idiosyncratic primitives,
334 most of them extremely important.
335* Autoloading:: Functions set up to load files
336 containing their real definitions.
337
338Control Structures
339
340* Sequencing:: Evaluation in textual order.
341* Conditionals:: @code{if}, @code{cond}.
342* Combining Conditions:: @code{and}, @code{or}, @code{not}.
343* Iteration:: @code{while} loops.
344* Nonlocal Exits:: Jumping out of a sequence.
345
346Nonlocal Exits
347
348* Catch and Throw:: Nonlocal exits for the program's own purposes.
349* Examples of Catch:: Showing how such nonlocal exits can be written.
350* Errors:: How errors are signaled and handled.
351* Cleanups:: Arranging to run a cleanup form if an
352 error happens.
353
354Errors
355
356* Signaling Errors:: How to report an error.
357* Processing of Errors:: What Emacs does when you report an error.
358* Handling Errors:: How you can trap errors and continue execution.
359* Error Names:: How errors are classified for trapping them.
360
361Variables
362
363* Global Variables:: Variable values that exist permanently, everywhere.
364* Constant Variables:: Certain "variables" have values that never change.
365* Local Variables:: Variable values that exist only temporarily.
366* Void Variables:: Symbols that lack values.
367* Defining Variables:: A definition says a symbol is used as a variable.
368* Accessing Variables:: Examining values of variables whose names
369 are known only at run time.
370* Setting Variables:: Storing new values in variables.
371* Variable Scoping:: How Lisp chooses among local and global values.
372* Buffer-Local Variables:: Variable values in effect only in one buffer.
373
374Scoping Rules for Variable Bindings
375
376* Scope:: Scope means where in the program a value
377 is visible. Comparison with other languages.
378* Extent:: Extent means how long in time a value exists.
379* Impl of Scope:: Two ways to implement dynamic scoping.
380* Using Scoping:: How to use dynamic scoping carefully and
381 avoid problems.
382
383Buffer-Local Variables
384
385* Intro to Buffer-Local:: Introduction and concepts.
386* Creating Buffer-Local:: Creating and destroying buffer-local bindings.
387* Default Value:: The default value is seen in buffers
388 that don't have their own local values.
389
390Functions
391
392* What Is a Function:: Lisp functions vs primitives; terminology.
393* Lambda Expressions:: How functions are expressed as Lisp objects.
394* Function Names:: A symbol can serve as the name of a function.
395* Defining Functions:: Lisp expressions for defining functions.
396* Calling Functions:: How to use an existing function.
397* Mapping Functions:: Applying a function to each element of a list, etc.
398* Anonymous Functions:: Lambda-expressions are functions with no names.
399* Function Cells:: Accessing or setting the function definition
400 of a symbol.
401* Related Topics:: Cross-references to specific Lisp primitives
402 that have a special bearing on how
403 functions work.
404
405Lambda Expressions
406
407* Lambda Components:: The parts of a lambda expression.
408* Simple Lambda:: A simple example.
409* Argument List:: Details and special features of argument lists.
410* Function Documentation:: How to put documentation in a function.
411
412Macros
413
414* Simple Macro:: A basic example.
415* Expansion:: How, when and why macros are expanded.
416* Compiling Macros:: How macros are expanded by the compiler.
417* Defining Macros:: How to write a macro definition.
418* Backquote:: Easier construction of list structure.
419* Problems with Macros:: Don't evaluate the macro arguments too many times.
420 Don't hide the user's variables.
421
422Loading
423
424* How Programs Do Loading:: The @code{load} function and others.
425* Autoload:: Setting up a function to autoload.
426* Features:: Loading a library if it isn't already loaded.
427* Repeated Loading:: Precautions about loading a file twice.
428
429Byte Compilation
430
431* Compilation Functions:: Byte compilation functions.
432* Disassembly:: Disassembling byte-code; how to read byte-code.
433
434Debugging Lisp Programs
435
436* Debugger:: How the Emacs Lisp debugger is implemented.
437* Syntax Errors:: How to find syntax errors.
438* Compilation Errors:: How to find errors that show up in
439 byte compilation.
440* Edebug:: A source-level Emacs Lisp debugger.
441
442The Lisp Debugger
443
444* Error Debugging:: Entering the debugger when an error happens.
445* Function Debugging:: Entering it when a certain function is called.
446* Explicit Debug:: Entering it at a certain point in the program.
447* Using Debugger:: What the debugger does; what you see while in it.
448* Debugger Commands:: Commands used while in the debugger.
449* Invoking the Debugger:: How to call the function @code{debug}.
450* Internals of Debugger:: Subroutines of the debugger, and global variables.
451
452Debugging Invalid Lisp Syntax
453
454* Excess Open:: How to find a spurious open paren or missing close.
455* Excess Close:: How to find a spurious close paren or missing open.
456
457Reading and Printing Lisp Objects
458
459* Streams Intro:: Overview of streams, reading and printing.
460* Input Streams:: Various data types that can be used as
461 input streams.
462* Input Functions:: Functions to read Lisp objects from text.
463* Output Streams:: Various data types that can be used as
464 output streams.
465* Output Functions:: Functions to print Lisp objects as text.
466
467Minibuffers
468
469* Intro to Minibuffers:: Basic information about minibuffers.
470* Text from Minibuffer:: How to read a straight text string.
471* Object from Minibuffer:: How to read a Lisp object or expression.
472* Completion:: How to invoke and customize completion.
473* Yes-or-No Queries:: Asking a question with a simple answer.
474* Minibuffer Misc:: Various customization hooks and variables.
475
476Completion
477
478* Basic Completion:: Low-level functions for completing strings.
479 (These are too low level to use the minibuffer.)
480* Minibuffer Completion:: Invoking the minibuffer with completion.
481* Completion Commands:: Minibuffer commands that do completion.
482* High-Level Completion:: Convenient special cases of completion
483 (reading buffer name, file name, etc.)
484* Reading File Names:: Using completion to read file names.
485* Programmed Completion:: Finding the completions for a given file name.
486
487Command Loop
488
489* Command Overview:: How the command loop reads commands.
490* Defining Commands:: Specifying how a function should read arguments.
491* Interactive Call:: Calling a command, so that it will read arguments.
492* Command Loop Info:: Variables set by the command loop for you to examine.
493* Input Events:: What input looks like when you read it.
494* Reading Input:: How to read input events from the keyboard or mouse.
495* Waiting:: Waiting for user input or elapsed time.
496* Quitting:: How @kbd{C-g} works. How to catch or defer quitting.
497* Prefix Command Arguments:: How the commands to set prefix args work.
498* Recursive Editing:: Entering a recursive edit,
499 and why you usually shouldn't.
500* Disabling Commands:: How the command loop handles disabled commands.
501* Command History:: How the command history is set up, and how accessed.
502* Keyboard Macros:: How keyboard macros are implemented.
503
504Defining Commands
505
506* Using Interactive:: General rules for @code{interactive}.
507* Interactive Codes:: The standard letter-codes for reading arguments
508 in various ways.
509* Interactive Examples:: Examples of how to read interactive arguments.
510
511Keymaps
512
513* Keymap Terminology:: Definitions of terms pertaining to keymaps.
514* Format of Keymaps:: What a keymap looks like as a Lisp object.
515* Creating Keymaps:: Functions to create and copy keymaps.
516* Inheritance and Keymaps:: How one keymap can inherit the bindings
517 of another keymap.
518* Prefix Keys:: Defining a key with a keymap as its definition.
519* Menu Keymaps:: A keymap can define a menu for X windows
520 or for use from the terminal.
521* Active Keymaps:: Each buffer has a local keymap
522 to override the standard (global) bindings.
523 Each minor mode can also override them.
524* Key Lookup:: How extracting elements from keymaps works.
525* Functions for Key Lookup:: How to request key lookup.
526* Changing Key Bindings:: Redefining a key in a keymap.
527* Key Binding Commands:: Interactive interfaces for redefining keys.
528* Scanning Keymaps:: Looking through all keymaps, for printing help.
529
530Major and Minor Modes
531
532* Major Modes:: Defining major modes.
533* Minor Modes:: Defining minor modes.
534* Mode Line Format:: Customizing the text that appears in the mode line.
535* Hooks:: How to use hooks; how to write code that
536 provides hooks.
537
538Major Modes
539
540* Major Mode Conventions:: Coding conventions for keymaps, etc.
541* Example Major Modes:: Text mode and Lisp modes.
542* Auto Major Mode:: How Emacs chooses the major mode automatically.
543* Mode Help:: Finding out how to use a mode.
544
545Minor Modes
546
547* Minor Mode Conventions:: Tips for writing a minor mode.
548* Keymaps and Minor Modes:: How a minor mode can have its own keymap.
549
550Mode Line Format
551
552* Mode Line Data:: The data structure that controls the mode line.
553* Mode Line Variables:: Variables used in that data structure.
554* %-Constructs:: Putting information into a mode line.
555
556Documentation
557
558* Documentation Basics:: Good style for doc strings.
559 Where to put them. How Emacs stores them.
560* Accessing Documentation:: How Lisp programs can access doc strings.
561* Keys in Documentation:: Substituting current key bindings.
562* Describing Characters:: Making printable descriptions of
563 non-printing characters and key sequences.
564* Help Functions:: Subroutines used by Emacs help facilities.
565
566Files
567
568* Visiting Files:: Reading files into Emacs buffers for editing.
569* Saving Buffers:: Writing changed buffers back into files.
570* Reading from Files:: Reading files into other buffers.
571* Writing to Files:: Writing new files from parts of buffers.
572* File Locks:: Locking and unlocking files, to prevent
573 simultaneous editing by two people.
574* Information about Files:: Testing existence, accessibility, size of files.
575* Contents of Directories:: Getting a list of the files in a directory.
576* Changing File Attributes:: Renaming files, changing protection, etc.
577* File Names:: Decomposing and expanding file names.
578
579Visiting Files
580
581* Visiting Functions:: The usual interface functions for visiting.
582* Subroutines of Visiting:: Lower-level subroutines that they use.
583
584Information about Files
585
586* Testing Accessibility:: Is a given file readable? Writable?
587* Kinds of Files:: Is it a directory? A link?
588* File Attributes:: How large is it? Any other names? Etc.
589
590File Names
591
592* File Name Components:: The directory part of a file name, and the rest.
593* Directory Names:: A directory's name as a directory
594 is different from its name as a file.
595* Relative File Names:: Some file names are relative to a
596 current directory.
597* File Name Expansion:: Converting relative file names to absolute ones.
598* Unique File Names:: Generating names for temporary files.
599* File Name Completion:: Finding the completions for a given file name.
600
601Backups and Auto-Saving
602
603* Backup Files:: How backup files are made; how their names
604 are chosen.
605* Auto-Saving:: How auto-save files are made; how their
606 names are chosen.
607* Reverting:: @code{revert-buffer}, and how to customize
608 what it does.
609
610Backup Files
611
612* Making Backups:: How Emacs makes backup files, and when.
613* Rename or Copy:: Two alternatives: renaming the old file
614 or copying it.
615* Numbered Backups:: Keeping multiple backups for each source file.
616* Backup Names:: How backup file names are computed; customization.
617
618Buffers
619
620* Buffer Basics:: What is a buffer?
621* Buffer Names:: Accessing and changing buffer names.
622* Buffer File Name:: The buffer file name indicates which file
623 is visited.
624* Buffer Modification:: A buffer is @dfn{modified} if it needs to be saved.
625* Modification Time:: Determining whether the visited file was changed
626 ``behind Emacs's back''.
627* Read Only Buffers:: Modifying text is not allowed in a
628 read-only buffer.
629* The Buffer List:: How to look at all the existing buffers.
630* Creating Buffers:: Functions that create buffers.
631* Killing Buffers:: Buffers exist until explicitly killed.
632* Current Buffer:: Designating a buffer as current
633 so primitives will access its contents.
634
635Windows
636
637* Basic Windows:: Basic information on using windows.
638* Splitting Windows:: Splitting one window into two windows.
639* Deleting Windows:: Deleting a window gives its space to other windows.
640* Selecting Windows:: The selected window is the one that you edit in.
641* Cyclic Window Ordering:: Moving around the existing windows.
642* Buffers and Windows:: Each window displays the contents of a buffer.
643* Displaying Buffers:: Higher-lever functions for displaying a buffer
644 and choosing a window for it.
645* Window Point:: Each window has its own location of point.
646* Window Start:: The display-start position controls which text
647 is on-screen in the window.
648* Vertical Scrolling:: Moving text up and down in the window.
649* Horizontal Scrolling:: Moving text sideways on the window.
650* Size of Window:: Accessing the size of a window.
651* Resizing Windows:: Changing the size of a window.
652* Window Configurations:: Saving and restoring the state of the screen.
653
654Positions
655
656* Point:: The special position where editing takes place.
657* Motion:: Changing point.
658* Excursions:: Temporary motion and buffer changes.
659* Narrowing:: Restricting editing to a portion of the buffer.
660
661Motion
662
663* Character Motion:: Moving in terms of characters.
664* Word Motion:: Moving in terms of words.
665* Buffer End Motion:: Moving to the beginning or end of the buffer.
666* Text Lines:: Moving in terms of lines of text.
667* Screen Lines:: Moving in terms of lines as displayed.
668* Vertical Motion:: Implementation of @code{next-line} and
669 @code{previous-line}.
670* List Motion:: Moving by parsing lists and sexps.
671* Skipping Characters:: Skipping characters belonging to a certain set.
672
673Markers
674
675* Overview of Markers:: The components of a marker, and how it relocates.
676* Predicates on Markers:: Testing whether an object is a marker.
677* Creating Markers:: Making empty markers or markers at certain places.
678* Information from Markers:: Finding the marker's buffer or character
679 position.
680* Changing Markers:: Moving the marker to a new buffer or position.
681* The Mark:: How ``the mark'' is implemented with a marker.
682* The Region:: How to access ``the region''.
683
684Text
685
686* Near Point:: Examining text in the vicinity of point.
687* Buffer Contents:: Examining text in a general fashion.
688* Insertion:: Adding new text to a buffer.
689* Commands for Insertion:: User-level commands to insert text.
690* Deletion:: Removing text from a buffer.
691* User-Level Deletion:: User-level commands to delete text.
692* The Kill Ring:: Where removed text sometimes is saved for
693 later use.
694* Undo:: Undoing changes to the text of a buffer.
695* Auto Filling:: How auto-fill mode is implemented to break lines.
696* Filling:: Functions for explicit filling.
697* Sorting:: Functions for sorting parts of the buffer.
698* Indentation:: Functions to insert or adjust indentation.
699* Columns:: Computing horizontal positions, and using them.
700* Case Changes:: Case conversion of parts of the buffer.
701* Substitution:: Replacing a given character wherever it appears.
702* Underlining:: Inserting or deleting underlining-by-overstrike.
703* Registers:: How registers are implemented. Accessing
704 the text or position stored in a register.
705
706The Kill Ring
707
708* Kill Ring Concepts:: What text looks like in the kill ring.
709* Kill Functions:: Functions that kill text.
710* Yank Commands:: Commands that access the kill ring.
711* Low Level Kill Ring:: Functions and variables for kill ring access.
712* Internals of Kill Ring:: Variables that hold kill-ring data.
713
714Indentation
715
716* Primitive Indent:: Functions used to count and insert indentation.
717* Mode-Specific Indent:: Customize indentation for different modes.
718* Region Indent:: Indent all the lines in a region.
719* Relative Indent:: Indent the current line based on previous lines.
720* Indent Tabs:: Adjustable, typewriter-like tab stops.
721* Motion by Indent:: Move to first non-blank character.
722
723Searching and Matching
724
725* String Search:: Search for an exact match.
726* Regular Expressions:: Describing classes of strings.
727* Regexp Search:: Searching for a match for a regexp.
728* Match Data:: Finding out which part of the text matched
729 various parts of a regexp, after regexp search.
730* Saving Match Data:: Saving and restoring this information.
731* Standard Regexps:: Useful regexps for finding sentences, pages,...
732* Searching and Case:: Case-independent or case-significant searching.
733
734Regular Expressions
735
736* Syntax of Regexps:: Rules for writing regular expressions.
737* Regexp Example:: Illustrates regular expression syntax.
738
739Syntax Tables
740
741* Syntax Descriptors:: How characters are classified.
742* Syntax Table Functions:: How to create, examine and alter syntax tables.
743* Parsing Expressions:: Parsing balanced expressions
744 using the syntax table.
745* Standard Syntax Tables:: Syntax tables used by various major modes.
746* Syntax Table Internals:: How syntax table information is stored.
747
748Syntax Descriptors
749
750* Syntax Class Table:: Table of syntax classes.
751* Syntax Flags:: Additional flags each character can have.
752
753Abbrevs And Abbrev Expansion
754
755* Abbrev Mode:: Setting up Emacs for abbreviation.
756* Tables: Abbrev Tables. Creating and working with abbrev tables.
757* Defining Abbrevs:: Specifying abbreviations and their expansions.
758* Files: Abbrev Files. Saving abbrevs in files.
759* Expansion: Abbrev Expansion. Controlling expansion; expansion subroutines.
760* Standard Abbrev Tables:: Abbrev tables used by various major modes.
761
762Processes
763
764* Subprocess Creation:: Functions that start subprocesses.
765* Synchronous Processes:: Details of using synchronous subprocesses.
766* Asynchronous Processes:: Starting up an asynchronous subprocess.
767* Deleting Processes:: Eliminating an asynchronous subprocess.
768* Process Information:: Accessing run-status and other attributes.
769* Input to Processes:: Sending input to an asynchronous subprocess.
770* Signals to Processes:: Stopping, continuing or interrupting
771 an asynchronous subprocess.
772* Output from Processes:: Collecting output from an asynchronous subprocess.
773* Sentinels:: Sentinels run when process run-status changes.
774* TCP:: Opening network connections.
775
776Receiving Output from Processes
777
778* Process Buffers:: If no filter, output is put in a buffer.
779* Filter Functions:: Filter functions accept output from the process.
780* Accepting Output:: How to wait until process output arrives.
781
782Operating System Interface
783
784* Starting Up:: Customizing Emacs start-up processing.
785* Getting Out:: How exiting works (permanent or temporary).
786* System Environment:: Distinguish the name and kind of system.
787* Terminal Input:: Recording terminal input for debugging.
788* Terminal Output:: Recording terminal output for debugging.
789* Flow Control:: How to turn output flow control on or off.
790* Batch Mode:: Running Emacs without terminal interaction.
791
792Starting Up Emacs
793
794* Start-up Summary:: Sequence of actions Emacs performs at start-up.
795* Init File:: Details on reading the init file (@file{.emacs}).
796* Terminal-Specific:: How the terminal-specific Lisp file is read.
797* Command Line Arguments:: How command line arguments are processed,
798 and how you can customize them.
799
800Getting out of Emacs
801
802* Killing Emacs:: Exiting Emacs irreversibly.
803* Suspending Emacs:: Exiting Emacs reversibly.
804
805Emacs Display
806
807* Refresh Screen:: Clearing the screen and redrawing everything on it.
808* Truncation:: Folding or wrapping long text lines.
809* The Echo Area:: Where messages are displayed.
810* Selective Display:: Hiding part of the buffer text.
811* Overlay Arrow:: Display of an arrow to indicate position.
812* Temporary Displays:: Displays that go away automatically.
813* Waiting:: Forcing display update and waiting for user.
814* Blinking:: How Emacs shows the matching open parenthesis.
815* Usual Display:: How control characters are displayed.
816* Beeping:: Audible signal to the user.
817* Window Systems:: Which window system is being used.
818
819GNU Emacs Internals
820
821* Building Emacs:: How to preload Lisp libraries into Emacs.
822* Pure Storage:: A kludge to make preloaded Lisp functions sharable.
823* Garbage Collection:: Reclaiming space for Lisp objects no longer used.
824* Object Internals:: Data formats of buffers, windows, processes.
825* Writing Emacs Primitives:: Writing C code for Emacs.
826
827Object Internals
828
829* Buffer Internals:: Components of a buffer structure.
830* Window Internals:: Components of a window structure.
831* Process Internals:: Components of a process structure.
832@end menu
833
834@include intro.texi
835@include objects.texi
836@include numbers.texi
837@include strings.texi
838
839@include lists.texi
840@include sequences.texi
841@include symbols.texi
842@include eval.texi
843
844@include control.texi
845@include variables.texi
846@include functions.texi
847@include macros.texi
848
849@include loading.texi
850@include compile.texi
851@include debugging.texi
852@include streams.texi
853
854@include minibuf.texi
855@include commands.texi
856@include keymaps.texi
857@include modes.texi
858
859@include help.texi
860@include files.texi
861@include backups.texi
862@include buffers.texi
863
864@include windows.texi
865@include frames.texi
866@include positions.texi
867@include markers.texi
868@include text.texi
869
870@include searching.texi
871@include syntax.texi
872@include abbrevs.texi
873
874@include processes.texi
875@include os.texi
876@include display.texi
877@include calendar.texi
878
879@c MOVE to Emacs Manual: include misc-modes.texi
880
881@c appendices
882
883@c REMOVE this: include non-hacker.texi
884
885@include tips.texi
886@include internals.texi
887@include errors.texi
888@include locals.texi
889@include maps.texi
890@include hooks.texi
891@include anti.texi
892
893@include index.texi
894
895@c Print the tables of contents
896@summarycontents
897@contents
898@c That's all
899
900@bye
901
902
903These words prevent "local variables" above from confusing Emacs.
diff --git a/lispref/internals.texi b/lispref/internals.texi
new file mode 100644
index 00000000000..64892ae6aed
--- /dev/null
+++ b/lispref/internals.texi
@@ -0,0 +1,807 @@
1@c -*-texinfo-*-
2@c This is part of the GNU Emacs Lisp Reference Manual.
3@c Copyright (C) 1990, 1991, 1992, 1993 Free Software Foundation, Inc.
4@c See the file elisp.texi for copying conditions.
5@setfilename ../info/internals
6@node GNU Emacs Internals, Standard Errors, Tips, Top
7@comment node-name, next, previous, up
8@appendix GNU Emacs Internals
9
10This chapter describes how the runnable Emacs executable is dumped with
11the preloaded Lisp libraries in it, how storage is allocated, and some
12internal aspects of GNU Emacs that may be of interest to C programmers.
13
14@menu
15* Building Emacs:: How to preload Lisp libraries into Emacs.
16* Pure Storage:: A kludge to make preloaded Lisp functions sharable.
17* Garbage Collection:: Reclaiming space for Lisp objects no longer used.
18* Writing Emacs Primitives:: Writing C code for Emacs.
19* Object Internals:: Data formats of buffers, windows, processes.
20@end menu
21
22@node Building Emacs, Pure Storage, GNU Emacs Internals, GNU Emacs Internals
23@appendixsec Building Emacs
24@cindex building Emacs
25@pindex temacs
26
27 This section explains the steps involved in building the Emacs
28executable. You don't have to know this material to build and install
29Emacs, since the makefiles do all these things automatically. This
30information is pertinent to Emacs maintenance.
31
32 Compilation of the C source files in the @file{src} directory
33produces an executable file called @file{temacs}, also called a
34@dfn{bare impure Emacs}. It contains the Emacs Lisp interpreter and I/O
35routines, but not the editing commands.
36
37@cindex @file{loadup.el}
38 The command @w{@samp{temacs -l loadup}} uses @file{temacs} to create
39the real runnable Emacs executable. These arguments direct
40@file{temacs} to evaluate the Lisp files specified in the file
41@file{loadup.el}. These files set up the normal Emacs editing
42environment, resulting in an Emacs which is still impure but no longer
43bare.
44
45 It takes a substantial time to load the standard Lisp files. Luckily,
46you don't have to do this each time you run Emacs; @file{temacs} can
47dump out an executable program called @file{emacs} which has these files
48preloaded. @file{emacs} starts more quickly because it does not need to
49load the files. This is the Emacs executable that is normally
50installed.
51
52 To create @file{emacs}, use the command @samp{temacs -batch -l loadup
53dump}. The purpose of @samp{-batch} here is to prevent @file{temacs}
54from trying to initialize any of its data on the terminal; this ensures
55that the tables of terminal information are empty in the dumped Emacs.
56The argument @samp{dump} tells @file{loadup.el} to dump a new executable
57named @file{emacs}.
58
59 Some operating systems don't support dumping. On those systems, you
60must start Emacs with the @samp{temacs -l loadup} command each time you
61use it. This takes a long time, but since you need to start Emacs once
62a day at most---or once a week if you never log out---the extra time is
63not too severe a problem.
64
65@cindex @file{site-load.el}
66 You can specify additional files to preload by writing a library named
67@file{site-load.el} which loads them. You may need to increase the
68value of @code{PURESIZE}, in @file{src/puresize.h}, to make room for the
69additional files. (Try adding increments of 20000 until it is big
70enough.) However, the advantage of preloading additional files
71decreases as machines get faster. On modern machines, it is usually not
72advisable.
73
74@cindex @file{site-init.el}
75 You can specify other things to be done in Lisp just before dumping by
76putting them in a library named @file{site-init.el}. However, if these
77things might alter the behavior that users expect from an ordinary
78unmodified Emacs, it is better to do them in @file{default.el}, so that
79users can override them if they wish. @xref{Start-up Summary}.
80
81 Before @file{emacs} is dumped, the documentation strings for primitive
82and preloaded functions (and variables) need to be found in the file
83where they are stored. This is done by calling
84@code{Snarf-documentation} (@pxref{Accessing Documentation}). These
85strings were moved out of @file{emacs} to make it smaller.
86@xref{Documentation Basics}.
87
88@defun dump-emacs to-file from-file
89@cindex unexec
90 This function dumps the current state of Emacs into an executable file
91@var{to-file}. It takes symbols from @var{from-file} (this is normally
92the executable file @file{temacs}).
93
94If you use this function in an Emacs that was already dumped, you must
95set @code{command-line-processed} to @code{nil} first for good results.
96@xref{Command Line Arguments}.
97@end defun
98
99@deffn Command emacs-version
100 This function returns a string describing the version of Emacs that is
101running. It is useful to include this string in bug reports.
102
103@example
104@group
105(emacs-version)
106 @result{} "GNU Emacs 19.22.1 of Fri Feb 27 1994 \
107on slug (berkeley-unix)"
108@end group
109@end example
110
111Called interactively, the function prints the same information in the
112echo area.
113@end deffn
114
115@defvar emacs-build-time
116 The value of this variable is the time at which Emacs was built at the
117local site.
118
119@example
120@group
121emacs-build-time
122 @result{} "Fri Feb 27 14:55:57 1994"
123@end group
124@end example
125@end defvar
126
127@defvar emacs-version
128The value of this variable is the version of Emacs being run. It is a
129string such as @code{"19.22.1"}.
130@end defvar
131
132@node Pure Storage, Garbage Collection, Building Emacs, GNU Emacs Internals
133@appendixsec Pure Storage
134@cindex pure storage
135
136 There are two types of storage in GNU Emacs Lisp for user-created Lisp
137objects: @dfn{normal storage} and @dfn{pure storage}. Normal storage is
138where all the new data which is created during an Emacs session is kept;
139see the following section for information on normal storage. Pure
140storage is used for certain data in the preloaded standard Lisp files:
141data that should never change during actual use of Emacs.
142
143 Pure storage is allocated only while @file{temacs} is loading the
144standard preloaded Lisp libraries. In the file @file{emacs}, it is
145marked as read-only (on operating systems which permit this), so that
146the memory space can be shared by all the Emacs jobs running on the
147machine at once. Pure storage is not expandable; a fixed amount is
148allocated when Emacs is compiled, and if that is not sufficient for the
149preloaded libraries, @file{temacs} crashes. If that happens, you will
150have to increase the compilation parameter @code{PURESIZE} in the file
151@file{src/puresize.h}. This normally won't happen unless you try to
152preload additional libraries or add features to the standard ones.
153
154@defun purecopy object
155 This function makes a copy of @var{object} in pure storage and returns
156it. It copies strings by simply making a new string with the same
157characters in pure storage. It recursively copies the contents of
158vectors and cons cells. It does not make copies of symbols, or any
159other objects, but just returns them unchanged. It signals an error if
160asked to copy markers.
161
162This function is used only while Emacs is being built and dumped; it is
163called only in the file @file{emacs/lisp/loaddefs.el}.
164@end defun
165
166@defvar pure-bytes-used
167 The value of this variable is the number of bytes of pure storage
168allocated so far. Typically, in a dumped Emacs, this number is very
169close to the total amount of pure storage available---if it were not,
170we would preallocate less.
171@end defvar
172
173@defvar purify-flag
174 This variable determines whether @code{defun} should make a copy of the
175function definition in pure storage. If it is non-@code{nil}, then the
176function definition is copied into pure storage.
177
178 This flag is @code{t} while loading all of the basic functions for
179building Emacs initially (allowing those functions to be sharable and
180non-collectible). It is set to @code{nil} when Emacs is saved out
181as @file{emacs}. The flag is set and reset in the C sources.
182
183 You should not change this flag in a running Emacs.
184@end defvar
185
186@node Garbage Collection, Writing Emacs Primitives, Pure Storage, GNU Emacs Internals
187@appendixsec Garbage Collection
188@cindex garbage collector
189
190@cindex memory allocation
191 When a program creates a list or the user defines a new function (such
192as by loading a library), then that data is placed in normal storage.
193If normal storage runs low, then Emacs asks the operating system to
194allocate more memory in blocks of 1k bytes. Each block is used for one
195type of Lisp object, so symbols, cons cells, markers, etc.@: are
196segregated in distinct blocks in memory. (Vectors, buffers and certain
197other editing types, which are fairly large, are allocated in individual
198blocks, one per object, while strings are packed into blocks of 8k
199bytes.)
200
201 It is quite common to use some storage for a while, then release it
202by, for example, killing a buffer or deleting the last pointer to an
203object. Emacs provides a @dfn{garbage collector} to reclaim this
204abandoned storage. (This name is traditional, but ``garbage recycler''
205might be a more intuitive metaphor for this facility.)
206
207 The garbage collector operates by scanning all the objects that have
208been allocated and marking those that are still accessible to Lisp
209programs. To begin with, all the symbols, their values and associated
210function definitions, and any data presently on the stack, are
211accessible. Any objects which can be reached indirectly through other
212accessible objects are also accessible.
213
214 When this is finished, all inaccessible objects are garbage. No
215matter what the Lisp program or the user does, it is impossible to refer
216to them, since there is no longer a way to reach them. Their
217space might as well be reused, since no one will notice. That is what
218the garbage collector arranges to do.
219
220@cindex free list
221 Unused cons cells are chained together onto a @dfn{free list} for
222future allocation; likewise for symbols and markers. The accessible
223strings are compacted so they are contiguous in memory; then the rest of
224the space formerly occupied by strings is made available to the string
225creation functions. Vectors, buffers, windows and other large objects
226are individually allocated and freed using @code{malloc}.
227
228@cindex CL note---allocate more storage
229@quotation
230@b{Common Lisp note:} unlike other Lisps, GNU Emacs Lisp does not
231call the garbage collector when the free list is empty. Instead, it
232simply requests the operating system to allocate more storage, and
233processing continues until @code{gc-cons-threshold} bytes have been
234used.
235
236This means that you can make sure that the garbage collector will not
237run during a certain portion of a Lisp program by calling the garbage
238collector explicitly just before it (provided that portion of the
239program does not use so much space as to force a second garbage
240collection).
241@end quotation
242
243@deffn Command garbage-collect
244 This command runs a garbage collection, and returns information on
245the amount of space in use. (Garbage collection can also occur
246spontaneously if you use more than @code{gc-cons-threshold} bytes of
247Lisp data since the previous garbage collection.)
248
249 @code{garbage-collect} returns a list containing the following
250information:
251
252@smallexample
253@group
254((@var{used-conses} . @var{free-conses})
255 (@var{used-syms} . @var{free-syms})
256 (@var{used-markers} . @var{free-markers})
257 @var{used-string-chars}
258 @var{used-vector-slots}
259 (@var{used-floats} . @var{free-floats}))
260
261(garbage-collect)
262 @result{} ((3435 . 2332) (1688 . 0)
263 (57 . 417) 24510 3839 (4 . 1))
264@end group
265@end smallexample
266
267Here is a table explaining each element:
268
269@table @var
270@item used-conses
271The number of cons cells in use.
272
273@item free-conses
274The number of cons cells for which space has been obtained from the
275operating system, but that are not currently being used.
276
277@item used-syms
278The number of symbols in use.
279
280@item free-syms
281The number of symbols for which space has been obtained from the
282operating system, but that are not currently being used.
283
284@item used-markers
285The number of markers in use.
286
287@item free-markers
288The number of markers for which space has been obtained from the
289operating system, but that are not currently being used.
290
291@item used-string-chars
292The total size of all strings, in characters.
293
294@item used-vector-slots
295The total number of elements of existing vectors.
296
297@item used-floats
298@c Emacs 19 feature
299The number of floats in use.
300
301@item free-floats
302@c Emacs 19 feature
303The number of floats for which space has been obtained from the
304operating system, but that are not currently being used.
305@end table
306@end deffn
307
308@defopt gc-cons-threshold
309 The value of this variable is the number of bytes of storage that must
310be allocated for Lisp objects after one garbage collection in order to
311request another garbage collection. A cons cell counts as eight bytes,
312a string as one byte per character plus a few bytes of overhead, and so
313on. (Space allocated to the contents of buffers does not count.) Note
314that the new garbage collection does not happen immediately when the
315threshold is exhausted, but only the next time the Lisp evaluator is
316called.
317
318 The initial threshold value is 100,000. If you specify a larger
319value, garbage collection will happen less often. This reduces the
320amount of time spent garbage collecting, but increases total memory use.
321You may want to do this when running a program which creates lots of
322Lisp data.
323
324 You can make collections more frequent by specifying a smaller value,
325down to 10,000. A value less than 10,000 will remain in effect only
326until the subsequent garbage collection, at which time
327@code{garbage-collect} will set the threshold back to 10,000.
328@end defopt
329
330@c Emacs 19 feature
331@defun memory-limit
332This function returns the address of the last byte Emacs has allocated,
333divided by 1024. We divide the value by 1024 to make sure it fits in a
334Lisp integer.
335
336You can use this to get a general idea of how your actions affect the
337memory usage.
338@end defun
339
340@node Writing Emacs Primitives, Object Internals, Garbage Collection, GNU Emacs Internals
341@appendixsec Writing Emacs Primitives
342@cindex primitive function internals
343
344 Lisp primitives are Lisp functions implemented in C. The details of
345interfacing the C function so that Lisp can call it are handled by a few
346C macros. The only way to really understand how to write new C code is
347to read the source, but we can explain some things here.
348
349 An example of a special form is the definition of @code{or}, from
350@file{eval.c}. (An ordinary function would have the same general
351appearance.)
352
353@cindex garbage collection protection
354@smallexample
355@group
356DEFUN ("or", For, Sor, 0, UNEVALLED, 0,
357 "Eval args until one of them yields non-NIL, then return that value.\n\
358The remaining args are not evalled at all.\n\
359@end group
360@group
361If all args return NIL, return NIL.")
362 (args)
363 Lisp_Object args;
364@{
365 register Lisp_Object val;
366 Lisp_Object args_left;
367 struct gcpro gcpro1;
368@end group
369
370@group
371 if (NULL(args))
372 return Qnil;
373
374 args_left = args;
375 GCPRO1 (args_left);
376@end group
377
378@group
379 do
380 @{
381 val = Feval (Fcar (args_left));
382 if (!NULL (val))
383 break;
384 args_left = Fcdr (args_left);
385 @}
386 while (!NULL(args_left));
387@end group
388
389@group
390 UNGCPRO;
391 return val;
392@}
393@end group
394@end smallexample
395
396 Let's start with a precise explanation of the arguments to the
397@code{DEFUN} macro. Here are the general names for them:
398
399@example
400DEFUN (@var{lname}, @var{fname}, @var{sname}, @var{min}, @var{max}, @var{interactive}, @var{doc})
401@end example
402
403@table @var
404@item lname
405This is the name of the Lisp symbol to define with this
406function; in the example above, it is @code{or}.
407
408@item fname
409This is the C function name for this function. This is
410the name that is used in C code for calling the function. The name is,
411by convention, @samp{F} prepended to the Lisp name, with all dashes
412(@samp{-}) in the Lisp name changed to underscores. Thus, to call this
413function from C code, call @code{For}. Remember that the arguments must
414be of type @code{Lisp_Object}; various macros and functions for creating
415values of type @code{Lisp_Object} are declared in the file
416@file{lisp.h}.
417
418@item sname
419This is a C variable name to use for a structure that holds the data for
420the subr object that represents the function in Lisp. This structure
421conveys the Lisp symbol name to the initialization routine that will
422create the symbol and store the subr object as its definition. By
423convention, this name is always @var{fname} with @samp{F} replaced with
424@samp{S}.
425
426@item min
427This is the minimum number of arguments that the function requires. For
428@code{or}, no arguments are required.
429
430@item max
431This is the maximum number of arguments that the function accepts.
432Alternatively, it can be @code{UNEVALLED}, indicating a special form
433that receives unevaluated arguments. A function with the equivalent of
434an @code{&rest} argument would have @code{MANY} in this position. Both
435@code{UNEVALLED} and @code{MANY} are macros. This argument must be one
436of these macros or a number at least as large as @var{min}. It may not
437be greater than six.
438
439@item interactive
440This is an interactive specification, a string such as might be used as
441the argument of @code{interactive} in a Lisp function. In the case of
442@code{or}, it is 0 (a null pointer), indicating that @code{or} cannot be
443called interactively. A value of @code{""} indicates an interactive
444function taking no arguments.
445
446@item doc
447This is the documentation string. It is written just like a
448documentation string for a function defined in Lisp, except you must
449write @samp{\n\} at the end of each line. In particular, the first line
450should be a single sentence.
451@end table
452
453 After the call to the @code{DEFUN} macro, you must write the list
454of argument names that every C function must have, followed by
455ordinary C declarations for them. Normally, all the arguments must
456be declared as @code{Lisp_Object}. If the function has no upper limit
457on the number of arguments in Lisp, then in C it receives two arguments:
458the number of Lisp arguments, and the address of a block containing their
459values. These have types @code{int} and @w{@code{Lisp_Object *}}.
460
461 Within the function @code{For} itself, note the use of the macros
462@code{GCPRO1} and @code{UNGCPRO}. @code{GCPRO1} is used to ``protect''
463a variable from garbage collection---to inform the garbage collector that
464it must look in that variable and regard its contents as an accessible
465object. This is necessary whenever you call @code{Feval} or anything
466that can directly or indirectly call @code{Feval}. At such a time, any
467Lisp object that you intend to refer to again must be protected somehow.
468@code{UNGCPRO} cancels the protection of the variables that are
469protected in the current function. It is necessary to do this explicitly.
470
471 For most data types, it suffices to know that one pointer to the
472object is protected; as long as the object is not recycled, all pointers
473to it remain valid. This is not so for strings, because the garbage
474collector can move them. When a string is moved, any pointers to it
475that the garbage collector does not know about will not be properly
476relocated. Therefore, all pointers to strings must be protected across
477any point where garbage collection may be possible.
478
479 The macro @code{GCPRO1} protects just one local variable. If you
480want to protect two, use @code{GCPRO2} instead; repeating @code{GCPRO1}
481will not work. There are also @code{GCPRO3} and @code{GCPRO4}.
482
483 In addition to using these macros, you must declare the local
484variables such as @code{gcpro1} which they implicitly use. If you
485protect two variables, with @code{GCPRO2}, you must declare
486@code{gcpro1} and @code{gcpro2}, as it uses them both. Alas, we can't
487explain all the tricky details here.
488
489 Defining the C function is not enough; you must also create the
490Lisp symbol for the primitive and store a suitable subr object
491in its function cell. This is done by adding code to an initialization
492routine. The code looks like this:
493
494@example
495defsubr (&@var{subr-structure-name});
496@end example
497
498@noindent
499@var{subr-structure-name} is the name you used as the third argument to
500@code{DEFUN}.
501
502 If you are adding a primitive to a file that already has Lisp
503primitives defined in it, find the function (near the end of the file)
504named @code{syms_of_@var{something}}, and add that function call to it.
505If the file doesn't have this function, or if you create a new file, add
506to it a @code{syms_of_@var{filename}} (e.g., @code{syms_of_myfile}).
507Then find the spot in @file{emacs.c} where all of these functions are
508called, and add a call to @code{syms_of_@var{filename}} there.
509
510 This function @code{syms_of_@var{filename}} is also the place to
511define any C variables which are to be visible as Lisp variables.
512@code{DEFVAR_LISP} is used to make a C variable of type
513@code{Lisp_Object} visible in Lisp. @code{DEFVAR_INT} is used to make a
514C variable of type @code{int} visible in Lisp with a value that is an
515integer.
516
517 Here is another function, with more complicated arguments. This comes
518from the code for the X Window System, and it demonstrates the use of
519macros and functions to manipulate Lisp objects.
520
521@smallexample
522@group
523DEFUN ("coordinates-in-window-p", Fcoordinates_in_window_p,
524 Scoordinates_in_window_p, 2, 2,
525 "xSpecify coordinate pair: \nXExpression which evals to window: ",
526 "Return non-nil if POSITIONS is in WINDOW.\n\
527 \(POSITIONS is a list, (SCREEN-X SCREEN-Y)\)\n\
528@end group
529@group
530 Returned value is list of positions expressed\n\
531 relative to window upper left corner.")
532 (coordinate, window)
533 register Lisp_Object coordinate, window;
534@{
535 register Lisp_Object xcoord, ycoord;
536@end group
537
538@group
539 if (!CONSP (coordinate)) wrong_type_argument (Qlistp, coordinate);
540 CHECK_WINDOW (window, 2);
541 xcoord = Fcar (coordinate);
542 ycoord = Fcar (Fcdr (coordinate));
543 CHECK_NUMBER (xcoord, 0);
544 CHECK_NUMBER (ycoord, 1);
545@end group
546@group
547 if ((XINT (xcoord) < XINT (XWINDOW (window)->left))
548 || (XINT (xcoord) >= (XINT (XWINDOW (window)->left)
549 + XINT (XWINDOW (window)->width))))
550 @{
551 return Qnil;
552 @}
553 XFASTINT (xcoord) -= XFASTINT (XWINDOW (window)->left);
554@end group
555@group
556 if (XINT (ycoord) == (screen_height - 1))
557 return Qnil;
558@end group
559@group
560 if ((XINT (ycoord) < XINT (XWINDOW (window)->top))
561 || (XINT (ycoord) >= (XINT (XWINDOW (window)->top)
562 + XINT (XWINDOW (window)->height)) - 1))
563 @{
564 return Qnil;
565 @}
566@end group
567@group
568 XFASTINT (ycoord) -= XFASTINT (XWINDOW (window)->top);
569 return (Fcons (xcoord, Fcons (ycoord, Qnil)));
570@}
571@end group
572@end smallexample
573
574 Note that you cannot directly call functions defined in Lisp as, for
575example, the primitive function @code{Fcons} is called above. You must
576create the appropriate Lisp form, protect everything from garbage
577collection, and @code{Feval} the form, as was done in @code{For} above.
578
579 @file{eval.c} is a very good file to look through for examples;
580@file{lisp.h} contains the definitions for some important macros and
581functions.
582
583@node Object Internals, , Writing Emacs Primitives, GNU Emacs Internals
584@appendixsec Object Internals
585@cindex object internals
586
587 GNU Emacs Lisp manipulates many different types of data. The actual
588data are stored in a heap and the only access that programs have to it is
589through pointers. Pointers are thirty-two bits wide in most
590implementations. Depending on the operating system and type of machine
591for which you compile Emacs, twenty-four to twenty-six bits are used to
592address the object, and the remaining six to eight bits are used for a
593tag that identifies the object's type.
594
595 Because all access to data is through tagged pointers, it is always
596possible to determine the type of any object. This allows variables to
597be untyped, and the values assigned to them to be changed without regard
598to type. Function arguments also can be of any type; if you want a
599function to accept only a certain type of argument, you must check the
600type explicitly using a suitable predicate (@pxref{Type Predicates}).
601@cindex type checking internals
602
603@menu
604* Buffer Internals:: Components of a buffer structure.
605* Window Internals:: Components of a window structure.
606* Process Internals:: Components of a process structure.
607@end menu
608
609@node Buffer Internals, Window Internals, Object Internals, Object Internals
610@appendixsubsec Buffer Internals
611@cindex internals, of buffer
612@cindex buffer internals
613
614 Buffers contain fields not directly accessible by the Lisp programmer.
615We describe them here, naming them by the names used in the C code.
616Many are accessible indirectly in Lisp programs via Lisp primitives.
617
618@table @code
619@item name
620The buffer name is a string which names the buffer. It is guaranteed to
621be unique. @xref{Buffer Names}.
622
623@item save_modified
624This field contains the time when the buffer was last saved, as an integer.
625@xref{Buffer Modification}.
626
627@item modtime
628This field contains the modification time of the visited file. It is
629set when the file is written or read. Every time the buffer is written
630to the file, this field is compared to the modification time of the
631file. @xref{Buffer Modification}.
632
633@item auto_save_modified
634This field contains the time when the buffer was last auto-saved.
635
636@item last_window_start
637This field contains the @code{window-start} position in the buffer as of
638the last time the buffer was displayed in a window.
639
640@item undodata
641This field points to the buffer's undo stack. @xref{Undo}.
642
643@item syntax_table_v
644This field contains the syntax table for the buffer. @xref{Syntax Tables}.
645
646@item downcase_table
647This field contains the conversion table for converting text to lower case.
648@xref{Case Table}.
649
650@item upcase_table
651This field contains the conversion table for converting text to upper case.
652@xref{Case Table}.
653
654@item case_canon_table
655This field contains the conversion table for canonicalizing text for
656case-folding search. @xref{Case Table}.
657
658@item case_eqv_table
659This field contains the equivalence table for case-folding search.
660@xref{Case Table}.
661
662@item display_table
663This field contains the buffer's display table, or @code{nil} if it doesn't
664have one. @xref{Display Tables}.
665
666@item markers
667This field contains the chain of all markers that point into the
668buffer. At each deletion or motion of the buffer gap, all of these
669markers must be checked and perhaps updated. @xref{Markers}.
670
671@item backed_up
672This field is a flag which tells whether a backup file has been made
673for the visited file of this buffer.
674
675@item mark
676This field contains the mark for the buffer. The mark is a marker,
677hence it is also included on the list @code{markers}. @xref{The Mark}.
678
679@item local_var_alist
680This field contains the association list containing all of the variables
681local in this buffer, and their values. The function
682@code{buffer-local-variables} returns a copy of this list.
683@xref{Buffer-Local Variables}.
684
685@item mode_line_format
686This field contains a Lisp object which controls how to display the mode
687line for this buffer. @xref{Mode Line Format}.
688@end table
689
690@node Window Internals, Process Internals, Buffer Internals, Object Internals
691@appendixsubsec Window Internals
692@cindex internals, of window
693@cindex window internals
694
695 Windows have the following accessible fields:
696
697@table @code
698@item frame
699 The frame that this window is on.
700
701@item mini_p
702 Non-@code{nil} if this window is a minibuffer window.
703
704@item height
705 The height of the window, measured in lines.
706
707@item width
708 The width of the window, measured in columns.
709
710@item buffer
711 The buffer which the window is displaying. This may change often during
712the life of the window.
713
714@item dedicated
715 Non-@code{nil} if this window is dedicated to its buffer.
716
717@item start
718 The position in the buffer which is the first character to be displayed
719in the window.
720
721@item pointm
722@cindex window point internals
723 This is the value of point in the current buffer when this window is
724selected; when it is not selected, it retains its previous value.
725
726@item left
727 This is the left-hand edge of the window, measured in columns. (The
728leftmost column on the screen is @w{column 0}.)
729
730@item top
731 This is the top edge of the window, measured in lines. (The top line on
732the screen is @w{line 0}.)
733
734@item next
735 This is the window that is the next in the chain of siblings.
736
737@item prev
738 This is the window that is the previous in the chain of siblings.
739
740@item force_start
741 This is a flag which, if non-@code{nil}, says that the window has been
742scrolled explicitly by the Lisp program. At the next redisplay, if
743point is off the screen, instead of scrolling the window to show the
744text around point, point will be moved to a location that is on the
745screen.
746
747@item hscroll
748 This is the number of columns that the display in the window is scrolled
749horizontally to the left. Normally, this is 0.
750
751@item use_time
752 This is the last time that the window was selected. The function
753@code{get-lru-window} uses this field.
754
755@item display_table
756 The window's display table, or @code{nil} if none is specified for it.
757@end table
758
759@node Process Internals, , Window Internals, Object Internals
760@appendixsubsec Process Internals
761@cindex internals, of process
762@cindex process internals
763
764 The fields of a process are:
765
766@table @code
767@item name
768A string, the name of the process.
769
770@item command
771A list containing the command arguments that were used to start this
772process.
773
774@item filter
775A function used to accept output from the process instead of a buffer,
776or @code{nil}.
777
778@item sentinel
779A function called whenever the process receives a signal, or @code{nil}.
780
781@item buffer
782The associated buffer of the process.
783
784@item pid
785An integer, the Unix process @sc{id}.
786
787@item childp
788A flag, non-@code{nil} if this is really a child process.
789It is @code{nil} for a network connection.
790
791@item flags
792A symbol indicating the state of the process. Possible values include
793@code{run}, @code{stop}, @code{closed}, etc.
794
795@item reason
796An integer, the Unix signal number that the process received that
797caused the process to terminate or stop. If the process has exited,
798then this is the exit code it specified.
799
800@item mark
801A marker indicating the position of end of last output from this process
802inserted into the buffer. This is usually the end of the buffer.
803
804@item kill_without_query
805A flag, non-@code{nil} meaning this process should not cause
806confirmation to be needed if Emacs is killed.
807@end table
diff --git a/lispref/maps.texi b/lispref/maps.texi
new file mode 100644
index 00000000000..b0cb0ab0bc8
--- /dev/null
+++ b/lispref/maps.texi
@@ -0,0 +1,133 @@
1@c -*-texinfo-*-
2@c This is part of the GNU Emacs Lisp Reference Manual.
3@c Copyright (C) 1990, 1991, 1992, 1993 Free Software Foundation, Inc.
4@c See the file elisp.texi for copying conditions.
5@setfilename ../info/maps
6@node Standard Keymaps, Standard Hooks, Standard Buffer-Local Variables, Top
7@appendix Standard Keymaps
8
9The following symbols are used as the names for various keymaps.
10Some of these exist when Emacs is first started, others are
11only loaded when their respective mode is used. This is not
12an exhaustive list.
13
14Almost all of these maps are used as local maps. Indeed, of the modes
15that presently exist, only Vip mode and Terminal mode ever change the
16global keymap.
17
18@table @code
19@item Buffer-menu-mode-map
20@vindex Buffer-menu-mode-map
21A full keymap used by Buffer Menu mode.
22
23@item c-mode-map
24@vindex c-mode-map
25A sparse keymap used in C mode as a local map.
26
27@item command-history-map
28@vindex command-history-map
29A full keymap used by Command History mode.
30
31@item ctl-x-4-map
32A sparse keymap for subcommands of the prefix @kbd{C-x 4}.
33
34@item ctl-x-map
35A full keymap for @kbd{C-x} commands.
36
37@item debugger-mode-map
38@vindex debugger-mode-map
39A full keymap used by Debugger mode.
40
41@item dired-mode-map
42@vindex dired-mode-map
43A full keymap for @code{dired-mode} buffers.
44
45@item doctor-mode-map
46@vindex doctor-mode-map
47A sparse keymap used by Doctor mode.
48
49@item edit-abbrevs-map
50@vindex edit-abbrevs-map
51A sparse keymap used in @code{edit-abbrevs}.
52
53@item edit-tab-stops-map
54@vindex edit-tab-stops-map
55A sparse keymap used in @code{edit-tab-stops}.
56
57@item electric-buffer-menu-mode-map
58@vindex electric-buffer-menu-mode-map
59A full keymap used by Electric Buffer Menu mode.
60
61@item electric-history-map
62@vindex electric-history-map
63A full keymap used by Electric Command History mode.
64
65@item emacs-lisp-mode-map
66@vindex emacs-lisp-mode-map
67A sparse keymap used in Emacs Lisp mode.
68
69@item function-key-map
70@vindex function-key-map
71The keymap for translating keypad and function keys.@*
72If there are none, then it contains an empty sparse keymap.
73
74@item fundamental-mode-map
75@vindex fundamental-mode-map
76The local keymap for Fundamental mode.@*
77It is empty and should not be changed.
78
79@item Helper-help-map
80@vindex Helper-help-map
81A full keymap used by the help utility package.@*
82It has the same keymap in its value cell and in its function
83cell.
84
85@item Info-edit-map
86@vindex Info-edit-map
87A sparse keymap used by the @kbd{e} command of Info.
88
89@item Info-mode-map
90@vindex Info-mode-map
91A sparse keymap containing Info commands.
92
93@item isearch-mode-map
94A keymap that defines the characters you can type within incremental
95search.
96
97@item key-translation-map
98@vindex key-translation-map
99Another keymap for translating keys. This one overrides ordinary key
100bindings.
101
102@item lisp-interaction-mode-map
103@vindex lisp-interaction-mode-map
104A sparse keymap used in Lisp mode.
105
106@item lisp-mode-map
107@vindex lisp-mode-map
108A sparse keymap used in Lisp mode.
109
110@item mode-specific-map
111The keymap for characters following @kbd{C-c}. Note, this is in the
112global map. This map is not actually mode specific: its name was chosen
113to be informative for the user in @kbd{C-h b} (@code{display-bindings}),
114where it describes the main use of the @kbd{C-c} prefix key.
115
116@item occur-mode-map
117@vindex occur-mode-map
118A local keymap used in Occur mode.
119
120@item query-replace-map
121A local keymap used for responses in @code{query-replace} and related
122commands; also for @code{y-or-n-p} and @code{map-y-or-n-p}. The functions
123that use this map do not support prefix keys; they look up one event at a
124time.
125
126@item text-mode-map
127@vindex text-mode-map
128A sparse keymap used by Text mode.
129
130@item view-mode-map
131@vindex view-mode-map
132A full keymap used by View mode.
133@end table
diff --git a/lispref/modes.texi b/lispref/modes.texi
new file mode 100644
index 00000000000..c15ca5a9cd0
--- /dev/null
+++ b/lispref/modes.texi
@@ -0,0 +1,1364 @@
1@c -*-texinfo-*-
2@c This is part of the GNU Emacs Lisp Reference Manual.
3@c Copyright (C) 1990, 1991, 1992, 1993, 1994 Free Software Foundation, Inc.
4@c See the file elisp.texi for copying conditions.
5@setfilename ../info/modes
6@node Modes, Documentation, Keymaps, Top
7@chapter Major and Minor Modes
8@cindex mode
9
10 A @dfn{mode} is a set of definitions that customize Emacs and can be
11turned on and off while you edit. There are two varieties of modes:
12@dfn{major modes}, which are mutually exclusive and used for editing
13particular kinds of text, and @dfn{minor modes}, which provide features
14that users can enable individually.
15
16 This chapter describes how to write both major and minor modes, how to
17indicate them in the mode line, and how they run hooks supplied by the
18user. For related topics such as keymaps and syntax tables, see
19@ref{Keymaps}, and @ref{Syntax Tables}.
20
21@menu
22* Major Modes:: Defining major modes.
23* Minor Modes:: Defining minor modes.
24* Mode Line Format:: Customizing the text that appears in the mode line.
25* Hooks:: How to use hooks; how to write code that provides hooks.
26@end menu
27
28@node Major Modes
29@section Major Modes
30@cindex major mode
31@cindex Fundamental mode
32
33 Major modes specialize Emacs for editing particular kinds of text.
34Each buffer has only one major mode at a time.
35
36 The least specialized major mode is called @dfn{Fundamental mode}.
37This mode has no mode-specific definitions or variable settings, so each
38Emacs command behaves in its default manner, and each option is in its
39default state. All other major modes redefine various keys and options.
40For example, Lisp Interaction mode provides special key bindings for
41@key{LFD} (@code{eval-print-last-sexp}), @key{TAB}
42(@code{lisp-indent-line}), and other keys.
43
44 When you need to write several editing commands to help you perform a
45specialized editing task, creating a new major mode is usually a good
46idea. In practice, writing a major mode is easy (in contrast to
47writing a minor mode, which is often difficult).
48
49 If the new mode is similar to an old one, it is often unwise to modify
50the old one to serve two purposes, since it may become harder to use and
51maintain. Instead, copy and rename an existing major mode definition
52and alter the copy---or define a @dfn{derived mode} (@pxref{Derived
53Modes}). For example, Rmail Edit mode, which is in
54@file{emacs/lisp/rmailedit.el}, is a major mode that is very similar to
55Text mode except that it provides three additional commands. Its
56definition is distinct from that of Text mode, but was derived from it.
57
58 Rmail Edit mode is an example of a case where one piece of text is put
59temporarily into a different major mode so it can be edited in a
60different way (with ordinary Emacs commands rather than Rmail). In such
61cases, the temporary major mode usually has a command to switch back to
62the buffer's usual mode (Rmail mode, in this case). You might be
63tempted to present the temporary redefinitions inside a recursive edit
64and restore the usual ones when the user exits; but this is a bad idea
65because it constrains the user's options when it is done in more than
66one buffer: recursive edits must be exited most-recently-entered first.
67Using alternative major modes avoids this limitation. @xref{Recursive
68Editing}.
69
70 The standard GNU Emacs Lisp library directory contains the code for
71several major modes, in files including @file{text-mode.el},
72@file{texinfo.el}, @file{lisp-mode.el}, @file{c-mode.el}, and
73@file{rmail.el}. You can look at these libraries to see how modes are
74written. Text mode is perhaps the simplest major mode aside from
75Fundamental mode. Rmail mode is a complicated and specialized mode.
76
77@menu
78* Major Mode Conventions:: Coding conventions for keymaps, etc.
79* Example Major Modes:: Text mode and Lisp modes.
80* Auto Major Mode:: How Emacs chooses the major mode automatically.
81* Mode Help:: Finding out how to use a mode.
82* Derived Modes:: Defining a new major mode based on another major
83 mode.
84@end menu
85
86@node Major Mode Conventions
87@subsection Major Mode Conventions
88
89 The code for existing major modes follows various coding conventions,
90including conventions for local keymap and syntax table initialization,
91global names, and hooks. Please follow these conventions when you
92define a new major mode:
93
94@itemize @bullet
95@item
96Define a command whose name ends in @samp{-mode}, with no arguments,
97that switches to the new mode in the current buffer. This command
98should set up the keymap, syntax table, and local variables in an
99existing buffer without changing the buffer's text.
100
101@item
102Write a documentation string for this command which describes the
103special commands available in this mode. @kbd{C-h m}
104(@code{describe-mode}) in your mode will display this string.
105
106The documentation string may include the special documentation
107substrings, @samp{\[@var{command}]}, @samp{\@{@var{keymap}@}}, and
108@samp{\<@var{keymap}>}, that enable the documentation to adapt
109automatically to the user's own key bindings. @xref{Keys in
110Documentation}.
111
112@item
113The major mode command should start by calling
114@code{kill-all-local-variables}. This is what gets rid of the local
115variables of the major mode previously in effect.
116
117@item
118The major mode command should set the variable @code{major-mode} to the
119major mode command symbol. This is how @code{describe-mode} discovers
120which documentation to print.
121
122@item
123The major mode command should set the variable @code{mode-name} to the
124``pretty'' name of the mode, as a string. This appears in the mode
125line.
126
127@item
128@cindex functions in modes
129Since all global names are in the same name space, all the global
130variables, constants, and functions that are part of the mode should
131have names that start with the major mode name (or with an abbreviation
132of it if the name is long). @xref{Style Tips}.
133
134@item
135@cindex keymaps in modes
136The major mode should usually have its own keymap, which is used as the
137local keymap in all buffers in that mode. The major mode function
138should call @code{use-local-map} to install this local map.
139@xref{Active Keymaps}, for more information.
140
141This keymap should be kept in a global variable named
142@code{@var{modename}-mode-map}. Normally the library that defines the
143mode sets this variable. Use @code{defvar} to set the variable, so that
144it is not reinitialized if it already has a value. (Such
145reinitialization could discard customizations made by the user.)
146
147@item
148@cindex syntax tables in modes
149The mode may have its own syntax table or may share one with other
150related modes. If it has its own syntax table, it should store this in
151a variable named @code{@var{modename}-mode-syntax-table}. The reasons
152for this are the same as for using a keymap variable. @xref{Syntax
153Tables}.
154
155@item
156@cindex abbrev tables in modes
157The mode may have its own abbrev table or may share one with other
158related modes. If it has its own abbrev table, it should store this in
159a variable named @code{@var{modename}-mode-abbrev-table}. @xref{Abbrev
160Tables}.
161
162@item
163@cindex buffer-local variables in modes
164To make a buffer-local binding for an Emacs customization variable, use
165@code{make-local-variable} in the major mode command, not
166@code{make-variable-buffer-local}. The latter function would make the
167variable local to every buffer in which it is subsequently set, which
168would affect buffers that do not use this mode. It is undesirable for a
169mode to have such global effects. @xref{Buffer-Local Variables}.
170
171It's ok to use @code{make-variable-buffer-local}, if you wish, for a
172variable used only within a single Lisp package.
173
174@item
175@cindex mode hook
176@cindex major mode hook
177Each major mode should have a @dfn{mode hook} named
178@code{@var{modename}-mode-hook}. The major mode command should run that
179hook, with @code{run-hooks}, as the very last thing it
180does. @xref{Hooks}.
181
182@item
183The major mode command may also run the hooks of some more basic modes.
184For example, @code{indented-text-mode} runs @code{text-mode-hook} as
185well as @code{indented-text-mode-hook}. It may run these other hooks
186immediately before the mode's own hook (that is, after everything else),
187or it may run them earlier.
188
189@item
190If something special should be done if the user switches a buffer from
191this mode to any other major mode, the mode can set a local value for
192@code{change-major-mode-hook}.
193
194@item
195If this mode is appropriate only for specially-prepared text, then the
196major mode command symbol should have a property named @code{mode-class}
197with value @code{special}, put on as follows:
198
199@cindex @code{mode-class} property
200@cindex @code{special}
201@example
202(put 'funny-mode 'mode-class 'special)
203@end example
204
205@noindent
206This tells Emacs that new buffers created while the current buffer has
207Funny mode should not inherit Funny mode. Modes such as Dired, Rmail,
208and Buffer List use this feature.
209
210@item
211If you want to make the new mode the default for files with certain
212recognizable names, add an element to @code{auto-mode-alist} to select
213the mode for those file names. If you define the mode command to
214autoload, you should add this element in the same file that calls
215@code{autoload}. Otherwise, it is sufficient to add the element in the
216file that contains the mode definition. @xref{Auto Major Mode}.
217
218@item
219@cindex @file{.emacs} customization
220In the documentation, you should provide a sample @code{autoload} form
221and an example of how to add to @code{auto-mode-alist}, that users can
222include in their @file{.emacs} files.
223
224@item
225@cindex mode loading
226The top level forms in the file defining the mode should be written so
227that they may be evaluated more than once without adverse consequences.
228Even if you never load the file more than once, someone else will.
229@end itemize
230
231@defvar change-major-mode-hook
232This normal hook is run by @code{kill-all-local-variables} before it
233does anything else. This gives major modes a way to arrange for
234something special to be done if the user switches to a different major
235mode. For best results, make this variable buffer-local, so that it
236will disappear after doing its job and will not interfere with the
237subsequent major mode.
238@end defvar
239
240@node Example Major Modes
241@subsection Major Mode Examples
242
243 Text mode is perhaps the simplest mode besides Fundamental mode.
244Here are excerpts from @file{text-mode.el} that illustrate many of
245the conventions listed above:
246
247@smallexample
248@group
249;; @r{Create mode-specific tables.}
250(defvar text-mode-syntax-table nil
251 "Syntax table used while in text mode.")
252@end group
253
254@group
255(if text-mode-syntax-table
256 () ; @r{Do not change the table if it is already set up.}
257 (setq text-mode-syntax-table (make-syntax-table))
258 (modify-syntax-entry ?\" ". " text-mode-syntax-table)
259 (modify-syntax-entry ?\\ ". " text-mode-syntax-table)
260 (modify-syntax-entry ?' "w " text-mode-syntax-table))
261@end group
262
263@group
264(defvar text-mode-abbrev-table nil
265 "Abbrev table used while in text mode.")
266(define-abbrev-table 'text-mode-abbrev-table ())
267@end group
268
269@group
270(defvar text-mode-map nil) ; @r{Create a mode-specific keymap.}
271
272(if text-mode-map
273 () ; @r{Do not change the keymap if it is already set up.}
274 (setq text-mode-map (make-sparse-keymap))
275 (define-key text-mode-map "\t" 'tab-to-tab-stop)
276 (define-key text-mode-map "\es" 'center-line)
277 (define-key text-mode-map "\eS" 'center-paragraph))
278@end group
279@end smallexample
280
281 Here is the complete major mode function definition for Text mode:
282
283@smallexample
284@group
285(defun text-mode ()
286 "Major mode for editing text intended for humans to read.
287 Special commands: \\@{text-mode-map@}
288@end group
289@group
290Turning on text-mode runs the hook `text-mode-hook'."
291 (interactive)
292 (kill-all-local-variables)
293@end group
294@group
295 (use-local-map text-mode-map) ; @r{This provides the local keymap.}
296 (setq mode-name "Text") ; @r{This name goes into the mode line.}
297 (setq major-mode 'text-mode) ; @r{This is how @code{describe-mode}}
298 ; @r{finds the doc string to print.}
299 (setq local-abbrev-table text-mode-abbrev-table)
300 (set-syntax-table text-mode-syntax-table)
301 (run-hooks 'text-mode-hook)) ; @r{Finally, this permits the user to}
302 ; @r{customize the mode with a hook.}
303@end group
304@end smallexample
305
306@cindex @file{lisp-mode.el}
307 The three Lisp modes (Lisp mode, Emacs Lisp mode, and Lisp
308Interaction mode) have more features than Text mode and the code is
309correspondingly more complicated. Here are excerpts from
310@file{lisp-mode.el} that illustrate how these modes are written.
311
312@cindex syntax table example
313@smallexample
314@group
315;; @r{Create mode-specific table variables.}
316(defvar lisp-mode-syntax-table nil "")
317(defvar emacs-lisp-mode-syntax-table nil "")
318(defvar lisp-mode-abbrev-table nil "")
319@end group
320
321@group
322(if (not emacs-lisp-mode-syntax-table) ; @r{Do not change the table}
323 ; @r{if it is already set.}
324 (let ((i 0))
325 (setq emacs-lisp-mode-syntax-table (make-syntax-table))
326@end group
327
328@group
329 ;; @r{Set syntax of chars up to 0 to class of chars that are}
330 ;; @r{part of symbol names but not words.}
331 ;; @r{(The number 0 is @code{48} in the @sc{ASCII} character set.)}
332 (while (< i ?0)
333 (modify-syntax-entry i "_ " emacs-lisp-mode-syntax-table)
334 (setq i (1+ i)))
335 @dots{}
336@end group
337@group
338 ;; @r{Set the syntax for other characters.}
339 (modify-syntax-entry ? " " emacs-lisp-mode-syntax-table)
340 (modify-syntax-entry ?\t " " emacs-lisp-mode-syntax-table)
341 @dots{}
342@end group
343@group
344 (modify-syntax-entry ?\( "() " emacs-lisp-mode-syntax-table)
345 (modify-syntax-entry ?\) ")( " emacs-lisp-mode-syntax-table)
346 @dots{}))
347;; @r{Create an abbrev table for lisp-mode.}
348(define-abbrev-table 'lisp-mode-abbrev-table ())
349@end group
350@end smallexample
351
352 Much code is shared among the three Lisp modes. The following
353function sets various variables; it is called by each of the major Lisp
354mode functions:
355
356@smallexample
357@group
358(defun lisp-mode-variables (lisp-syntax)
359 ;; @r{The @code{lisp-syntax} argument is @code{nil} in Emacs Lisp mode,}
360 ;; @r{and @code{t} in the other two Lisp modes.}
361 (cond (lisp-syntax
362 (if (not lisp-mode-syntax-table)
363 ;; @r{The Emacs Lisp mode syntax table always exists, but}
364 ;; @r{the Lisp Mode syntax table is created the first time a}
365 ;; @r{mode that needs it is called. This is to save space.}
366@end group
367@group
368 (progn (setq lisp-mode-syntax-table
369 (copy-syntax-table emacs-lisp-mode-syntax-table))
370 ;; @r{Change some entries for Lisp mode.}
371 (modify-syntax-entry ?\| "\" "
372 lisp-mode-syntax-table)
373 (modify-syntax-entry ?\[ "_ "
374 lisp-mode-syntax-table)
375 (modify-syntax-entry ?\] "_ "
376 lisp-mode-syntax-table)))
377@end group
378@group
379 (set-syntax-table lisp-mode-syntax-table)))
380 (setq local-abbrev-table lisp-mode-abbrev-table)
381 @dots{})
382@end group
383@end smallexample
384
385 Functions such as @code{forward-paragraph} use the value of the
386@code{paragraph-start} variable. Since Lisp code is different from
387ordinary text, the @code{paragraph-start} variable needs to be set
388specially to handle Lisp. Also, comments are indented in a special
389fashion in Lisp and the Lisp modes need their own mode-specific
390@code{comment-indent-function}. The code to set these variables is the
391rest of @code{lisp-mode-variables}.
392
393@smallexample
394@group
395 (make-local-variable 'paragraph-start)
396 (setq paragraph-start (concat "^$\\|" page-delimiter))
397 @dots{}
398@end group
399@group
400 (make-local-variable 'comment-indent-function)
401 (setq comment-indent-function 'lisp-comment-indent))
402@end group
403@end smallexample
404
405 Each of the different Lisp modes has a slightly different keymap. For
406example, Lisp mode binds @kbd{C-c C-l} to @code{run-lisp}, but the other
407Lisp modes do not. However, all Lisp modes have some commands in
408common. The following function adds these common commands to a given
409keymap.
410
411@smallexample
412@group
413(defun lisp-mode-commands (map)
414 (define-key map "\e\C-q" 'indent-sexp)
415 (define-key map "\177" 'backward-delete-char-untabify)
416 (define-key map "\t" 'lisp-indent-line))
417@end group
418@end smallexample
419
420 Here is an example of using @code{lisp-mode-commands} to initialize a
421keymap, as part of the code for Emacs Lisp mode. First we declare a
422variable with @code{defvar} to hold the mode-specific keymap. When this
423@code{defvar} executes, it sets the variable to @code{nil} if it was
424void. Then we set up the keymap if the variable is @code{nil}.
425
426 This code avoids changing the keymap or the variable if it is already
427set up. This lets the user customize the keymap if he or she so
428wishes.
429
430@smallexample
431@group
432(defvar emacs-lisp-mode-map () "")
433(if emacs-lisp-mode-map
434 ()
435 (setq emacs-lisp-mode-map (make-sparse-keymap))
436 (define-key emacs-lisp-mode-map "\e\C-x" 'eval-defun)
437 (lisp-mode-commands emacs-lisp-mode-map))
438@end group
439@end smallexample
440
441 Finally, here is the complete major mode function definition for
442Emacs Lisp mode.
443
444@smallexample
445@group
446(defun emacs-lisp-mode ()
447 "Major mode for editing Lisp code to run in Emacs.
448Commands:
449Delete converts tabs to spaces as it moves back.
450Blank lines separate paragraphs. Semicolons start comments.
451\\@{emacs-lisp-mode-map@}
452@end group
453@group
454Entry to this mode runs the hook `emacs-lisp-mode-hook'."
455 (interactive)
456 (kill-all-local-variables)
457 (use-local-map emacs-lisp-mode-map) ; @r{This provides the local keymap.}
458 (set-syntax-table emacs-lisp-mode-syntax-table)
459@end group
460@group
461 (setq major-mode 'emacs-lisp-mode) ; @r{This is how @code{describe-mode}}
462 ; @r{finds out what to describe.}
463 (setq mode-name "Emacs-Lisp") ; @r{This goes into the mode line.}
464 (lisp-mode-variables nil) ; @r{This define various variables.}
465 (run-hooks 'emacs-lisp-mode-hook)) ; @r{This permits the user to use a}
466 ; @r{hook to customize the mode.}
467@end group
468@end smallexample
469
470@node Auto Major Mode
471@subsection How Emacs Chooses a Major Mode
472
473 Based on information in the file name or in the file itself, Emacs
474automatically selects a major mode for the new buffer when a file is
475visited.
476
477@deffn Command fundamental-mode
478 Fundamental mode is a major mode that is not specialized for anything
479in particular. Other major modes are defined in effect by comparison
480with this one---their definitions say what to change, starting from
481Fundamental mode. The @code{fundamental-mode} function does @emph{not}
482run any hooks; you're not supposed to customize it. (If you want Emacs
483to behave differently in Fundamental mode, change the @emph{global}
484state of Emacs.)
485@end deffn
486
487@deffn Command normal-mode &optional find-file
488 This function establishes the proper major mode and local variable
489bindings for the current buffer. First it calls @code{set-auto-mode},
490then it runs @code{hack-local-variables} to parse, and bind or
491evaluate as appropriate, any local variables.
492
493 If the @var{find-file} argument to @code{normal-mode} is
494non-@code{nil}, @code{normal-mode} assumes that the @code{find-file}
495function is calling it. In this case, it may process a local variables
496list at the end of the file. The variable @code{enable-local-variables}
497controls whether to do so.
498
499 If you run @code{normal-mode} interactively, the argument
500@var{find-file} is normally @code{nil}. In this case,
501@code{normal-mode} unconditionally processes any local variables list.
502@xref{File variables, , Local Variables in Files, emacs, The GNU Emacs
503Manual}, for the syntax of the local variables section of a file.
504
505@cindex file mode specification error
506 @code{normal-mode} uses @code{condition-case} around the call to the
507major mode function, so errors are caught and reported as a @samp{File
508mode specification error}, followed by the original error message.
509@end deffn
510
511@defopt enable-local-variables
512This variable controls processing of local variables lists in files
513being visited. A value of @code{t} means process the local variables
514lists unconditionally; @code{nil} means ignore them; anything else means
515ask the user what to do for each file. The default value is @code{t}.
516@end defopt
517
518@defopt enable-local-eval
519This variable controls processing of @samp{Eval:} in local variables
520lists in files being visited. A value of @code{t} means process them
521unconditionally; @code{nil} means ignore them; anything else means ask
522the user what to do for each file. The default value is @code{maybe}.
523@end defopt
524
525@defun set-auto-mode
526@cindex visited file mode
527 This function selects the major mode that is appropriate for the
528current buffer. It may base its decision on the value of the @w{@samp{-*-}}
529line, on the visited file name (using @code{auto-mode-alist}), or on the
530value of a local variable). However, this function does not look for
531the @samp{mode:} local variable near the end of a file; the
532@code{hack-local-variables} function does that. @xref{Choosing Modes, ,
533How Major Modes are Chosen, emacs, The GNU Emacs Manual}.
534@end defun
535
536@defopt default-major-mode
537 This variable holds the default major mode for new buffers. The
538standard value is @code{fundamental-mode}.
539
540 If the value of @code{default-major-mode} is @code{nil}, Emacs uses
541the (previously) current buffer's major mode for the major mode of a new
542buffer. However, if the major mode symbol has a @code{mode-class}
543property with value @code{special}, then it is not used for new buffers;
544Fundamental mode is used instead. The modes that have this property are
545those such as Dired and Rmail that are useful only with text that has
546been specially prepared.
547@end defopt
548
549@defvar initial-major-mode
550@cindex @samp{*scratch*}
551The value of this variable determines the major mode of the initial
552@samp{*scratch*} buffer. The value should be a symbol that is a major
553mode command name. The default value is @code{lisp-interaction-mode}.
554@end defvar
555
556@defvar auto-mode-alist
557This variable contains an association list of file name patterns
558(regular expressions; @pxref{Regular Expressions}) and corresponding
559major mode functions. Usually, the file name patterns test for
560suffixes, such as @samp{.el} and @samp{.c}, but this need not be the
561case. An ordinary element of the alist looks like @code{(@var{regexp} .
562@var{mode-function})}.
563
564For example,
565
566@smallexample
567@group
568(("^/tmp/fol/" . text-mode)
569 ("\\.texinfo$" . texinfo-mode)
570 ("\\.texi$" . texinfo-mode)
571@end group
572@group
573 ("\\.el$" . emacs-lisp-mode)
574 ("\\.c$" . c-mode)
575 ("\\.h$" . c-mode)
576 @dots{})
577@end group
578@end smallexample
579
580When you visit a file whose expanded file name (@pxref{File Name
581Expansion}) matches a @var{regexp}, @code{set-auto-mode} calls the
582corresponding @var{mode-function}. This feature enables Emacs to select
583the proper major mode for most files.
584
585If an element of @code{auto-mode-alist} has the form @code{(@var{regexp}
586@var{function} t)}, then after calling @var{function}, Emacs searches
587@code{auto-mode-alist} again for a match against the portion of the file
588name that did not match before.
589
590This match-again feature is useful for uncompression packages: an entry
591of the form @code{("\\.gz\\'" . @var{function})} can uncompress the file
592and then put the uncompressed file in the proper mode according to the
593name sans @samp{.gz}.
594
595Here is an example of how to prepend several pattern pairs to
596@code{auto-mode-alist}. (You might use this sort of expression in your
597@file{.emacs} file.)
598
599@smallexample
600@group
601(setq auto-mode-alist
602 (append
603 ;; @r{Filename starts with a dot.}
604 '(("/\\.[^/]*$" . fundamental-mode)
605 ;; @r{Filename has no dot.}
606 ("[^\\./]*$" . fundamental-mode)
607 ("\\.C$" . c++-mode))
608 auto-mode-alist))
609@end group
610@end smallexample
611@end defvar
612
613@defvar interpreter-mode-alist
614This variable specifes major modes to use for scripts that specify a
615command interpreter in an @samp{!#} line. Its value is a list of
616elements of the form @code{(@var{interpreter} . @var{mode})}; for
617example, @code{("perl" . perl-mode)} is one element present by default.
618The element says to use mode @var{mode} if the file specifies
619@var{interpreter}.
620
621This variable is applicable only when the file name doesn't indicate
622which major mode to use.
623@end defvar
624
625@defun hack-local-variables &optional force
626 This function parses, and binds or evaluates as appropriate, any local
627variables for the current buffer.
628
629 The handling of @code{enable-local-variables} documented for
630@code{normal-mode} actually takes place here. The argument @var{force}
631reflects the argument @var{find-file} given to @code{normal-mode}.
632@end defun
633
634@node Mode Help
635@subsection Getting Help about a Major Mode
636@cindex mode help
637@cindex help for major mode
638@cindex documentation for major mode
639
640 The @code{describe-mode} function is used to provide information
641about major modes. It is normally called with @kbd{C-h m}. The
642@code{describe-mode} function uses the value of @code{major-mode},
643which is why every major mode function needs to set the
644@code{major-mode} variable.
645
646@deffn Command describe-mode
647This function displays the documentation of the current major mode.
648
649The @code{describe-mode} function calls the @code{documentation}
650function using the value of @code{major-mode} as an argument. Thus, it
651displays the documentation string of the major mode function.
652(@xref{Accessing Documentation}.)
653@end deffn
654
655@defvar major-mode
656This variable holds the symbol for the current buffer's major mode.
657This symbol should have a function definition which is the command to
658switch to that major mode. The @code{describe-mode} function uses the
659documentation string of this symbol as the documentation of the major
660mode.
661@end defvar
662
663@node Derived Modes
664@subsection Defining Derived Modes
665
666 It's often useful to define a new major mode in terms of an existing
667one. An easy way to do this is to use @code{define-derived-mode}.
668
669@defmac define-derived-mode variant parent name doc body@dots{}
670This construct defines @var{variant} as a major mode command, using
671@var{name} as the string form of the mode which.
672
673The definition of the command is to call the function @var{parent}, then
674override certain aspects of that parent mode:
675
676@itemize @bullet
677@item
678The new mode has its own keymap, named @code{@var{variant}-map}.
679@code{define-derived-mode} initializes this map to inherit from
680@code{@var{parent}-map}, if it is not already set.
681
682@item
683The new mode has its own syntax table, taken from the variable
684@code{@var{variant}-syntax-table}.
685@code{define-derived-mode} initializes this variable by copying
686@code{@var{parent}-syntax-table}, if it is not already set.
687
688@item
689The new mode has its own abbrev table, taken from the variable
690@code{@var{variant}-abbrev-table}.
691@code{define-derived-mode} initializes this variable by copying
692@code{@var{parent}-abbrev-table}, if it is not already set.
693
694@item
695The new mode has its own mode hook, @code{@var{variant}-hook},
696which it runs in standard fashion as the very last thing that it does.
697(The new mode also runs the mode hook of @var{parent} as part
698of calling @var{parent}.)
699@end itemize
700
701In addition, you can specify how to override other aspects of
702@var{parent-mode} with @var{body}. The command @var{variant}
703evaluates the forms in @var{body} after setting up all its usual
704overrides, just before running @code{@var{variant}-hook}.
705
706The argument @var{docstring} specifies the documentation string for the
707new mode. If you omit @var{docstring}, @code{define-derived-mode}
708generates a documentation string.
709
710Here is a hypothetical example:
711
712@example
713(define-derived-mode hypertext-mode
714 text-mode "Hypertext"
715 "Major mode for hypertext.
716\\@{hypertext-mode-map@}"
717 (setq case-fold-search nil))
718
719(define-key hypertext-mode-map
720 [down-mouse-3] 'do-hyper-link)
721@end example
722@end defmac
723
724@node Minor Modes
725@section Minor Modes
726@cindex minor mode
727
728 A @dfn{minor mode} provides features that users may enable or disable
729independently of the choice of major mode. Minor modes can be enabled
730individually or in combination. Minor modes would be better named
731``Generally available, optional feature modes'' except that such a name is
732unwieldy.
733
734 A minor mode is not usually a modification of single major mode. For
735example, Auto Fill mode may be used in any major mode that permits text
736insertion. To be general, a minor mode must be effectively independent
737of the things major modes do.
738
739 A minor mode is often much more difficult to implement than a major
740mode. One reason is that you should be able to activate and deactivate
741minor modes in any order.
742
743and restore the environment of the major mode to the state it was in
744before the minor mode was activated.
745
746 Often the biggest problem in implementing a minor mode is finding a
747way to insert the necessary hook into the rest of Emacs. Minor mode
748keymaps make this easier in Emacs 19 than it used to be.
749
750@menu
751* Minor Mode Conventions:: Tips for writing a minor mode.
752* Keymaps and Minor Modes:: How a minor mode can have its own keymap.
753@end menu
754
755@node Minor Mode Conventions
756@subsection Conventions for Writing Minor Modes
757@cindex minor mode conventions
758@cindex conventions for writing minor modes
759
760 There are conventions for writing minor modes just as there are for
761major modes. Several of the major mode conventions apply to minor
762modes as well: those regarding the name of the mode initialization
763function, the names of global symbols, and the use of keymaps and
764other tables.
765
766 In addition, there are several conventions that are specific to
767minor modes.
768
769@itemize @bullet
770@item
771@cindex mode variable
772Make a variable whose name ends in @samp{-mode} to represent the minor
773mode. Its value should enable or disable the mode (@code{nil} to
774disable; anything else to enable.) We call this the @dfn{mode
775variable}.
776
777This variable is used in conjunction with the @code{minor-mode-alist} to
778display the minor mode name in the mode line. It can also enable
779or disable a minor mode keymap. Individual commands or hooks can also
780check the variable's value.
781
782If you want the minor mode to be enabled separately in each buffer,
783make the variable buffer-local.
784
785@item
786Define a command whose name is the same as the mode variable.
787Its job is to enable and disable the mode by setting the variable.
788
789The command should accept one optional argument. If the argument is
790@code{nil}, it should toggle the mode (turn it on if it is off, and off
791if it is on). Otherwise, it should turn the mode on if the argument is
792a positive integer, a symbol other than @code{nil} or @code{-}, or a
793list whose @sc{car} is such an integer or symbol; it should turn the
794mode off otherwise.
795
796Here is an example taken from the definition of @code{overwrite-mode}.
797It shows the use of @code{overwrite-mode} as a variable which enables or
798disables the mode's behavior.
799
800@smallexample
801@group
802(setq overwrite-mode
803 (if (null arg) (not overwrite-mode)
804 (> (prefix-numeric-value arg) 0)))
805@end group
806@end smallexample
807
808@item
809Add an element to @code{minor-mode-alist} for each minor mode
810(@pxref{Mode Line Variables}). This element should be a list of the
811following form:
812
813@smallexample
814(@var{mode-variable} @var{string})
815@end smallexample
816
817Here @var{mode-variable} is the variable that controls enablement of the
818minor mode, and @var{string} is a short string, starting with a space,
819to represent the mode in the mode line. These strings must be short so
820that there is room for several of them at once.
821
822When you add an element to @code{minor-mode-alist}, use @code{assq} to
823check for an existing element, to avoid duplication. For example:
824
825@smallexample
826@group
827(or (assq 'leif-mode minor-mode-alist)
828 (setq minor-mode-alist
829 (cons '(leif-mode " Leif") minor-mode-alist)))
830@end group
831@end smallexample
832@end itemize
833
834@node Keymaps and Minor Modes
835@subsection Keymaps and Minor Modes
836
837As of Emacs version 19, each minor mode can have its own keymap which is
838active when the mode is enabled. @xref{Active Keymaps}. To set up a
839keymap for a minor mode, add an element to the alist
840@code{minor-mode-map-alist}.
841
842@cindex @code{self-insert-command}, minor modes
843One use of minor mode keymaps is to modify the behavior of certain
844self-inserting characters so that they do something else as well as
845self-insert. In general, this is the only way to do that, since the
846facilities for customizing @code{self-insert-command} are limited to
847special cases (designed for abbrevs and Auto Fill mode). (Do not try
848substituting your own definition of @code{self-insert-command} for the
849standard one. The editor command loop handles this function specially.)
850
851@defvar minor-mode-map-alist
852This variable is an alist of elements that look like this:
853
854@example
855(@var{variable} . @var{keymap})
856@end example
857
858@noindent
859where @var{variable} is the variable which indicates whether the minor
860mode is enabled, and @var{keymap} is the keymap. The keymap
861@var{keymap} is active whenever @var{variable} has a non-@code{nil}
862value.
863
864Note that elements of @code{minor-mode-map-alist} do not have the same
865structure as elements of @code{minor-mode-alist}. The map must be the
866@sc{cdr} of the element; a list with the map as the second element will
867not do.
868
869What's more, the keymap itself must appear in the @sc{cdr}. It does not
870work to store a variable in the @sc{cdr} and make the map the value of
871that variable.
872
873When more than one minor mode keymap is active, their order of priority
874is the order of @code{minor-mode-map-alist}. But you should design
875minor modes so that they don't interfere with each other. If you do
876this properly, the order will not matter.
877@end defvar
878
879@node Mode Line Format
880@section Mode Line Format
881@cindex mode line
882
883 Each Emacs window (aside from minibuffer windows) includes a mode line
884which displays status information about the buffer displayed in the
885window. The mode line contains information about the buffer such as its
886name, associated file, depth of recursive editing, and the major and
887minor modes of the buffer.
888
889 This section describes how the contents of the mode line are
890controlled. It is in the chapter on modes because much of the
891information displayed in the mode line relates to the enabled major and
892minor modes.
893
894 @code{mode-line-format} is a buffer-local variable that holds a
895template used to display the mode line of the current buffer. All
896windows for the same buffer use the same @code{mode-line-format} and the
897mode lines will appear the same (except for scrolling percentages and
898line numbers).
899
900 The mode line of a window is normally updated whenever a different
901buffer is shown in the window, or when the buffer's modified-status
902changes from @code{nil} to @code{t} or vice-versa. If you modify any of
903the variables referenced by @code{mode-line-format}, you may want to
904force an update of the mode line so as to display the new information.
905
906@c Emacs 19 feature
907@defun force-mode-line-update
908Force redisplay of the current buffer's mode line.
909@end defun
910
911 The mode line is usually displayed in inverse video; see
912@code{mode-line-inverse-video} in @ref{Inverse Video}.
913
914@menu
915* Mode Line Data:: The data structure that controls the mode line.
916* Mode Line Variables:: Variables used in that data structure.
917* %-Constructs:: Putting information into a mode line.
918@end menu
919
920@node Mode Line Data
921@subsection The Data Structure of the Mode Line
922@cindex mode line construct
923
924 The mode line contents are controlled by a data structure of lists,
925strings, symbols and numbers kept in the buffer-local variable
926@code{mode-line-format}. The data structure is called a @dfn{mode line
927construct}, and it is built in recursive fashion out of simpler mode line
928constructs.
929
930@defvar mode-line-format
931The value of this variable is a mode line construct with overall
932responsibility for the mode line format. The value of this variable
933controls which other variables are used to form the mode line text, and
934where they appear.
935@end defvar
936
937 A mode line construct may be as simple as a fixed string of text, but
938it usually specifies how to use other variables to construct the text.
939Many of these variables are themselves defined to have mode line
940constructs as their values.
941
942 The default value of @code{mode-line-format} incorporates the values
943of variables such as @code{mode-name} and @code{minor-mode-alist}.
944Because of this, very few modes need to alter @code{mode-line-format}.
945For most purposes, it is sufficient to alter the variables referenced by
946@code{mode-line-format}.
947
948 A mode line construct may be a list, cons cell, symbol, or string. If
949the value is a list, each element may be a list, a cons cell, a symbol,
950or a string.
951
952@table @code
953@cindex percent symbol in mode line
954@item @var{string}
955A string as a mode line construct is displayed verbatim in the mode line
956except for @dfn{@code{%}-constructs}. Decimal digits after the @code{%}
957specify the field width for space filling on the right (i.e., the data
958is left justified). @xref{%-Constructs}.
959
960@item @var{symbol}
961A symbol as a mode line construct stands for its value. The value of
962@var{symbol} is used in place of @var{symbol} unless @var{symbol} is
963@code{t} or @code{nil}, or is void, in which case @var{symbol} is
964ignored.
965
966There is one exception: if the value of @var{symbol} is a string, it is
967processed verbatim in that the @code{%}-constructs are not recognized.
968
969@item (@var{string} @var{rest}@dots{}) @r{or} (@var{list} @var{rest}@dots{})
970A list whose first element is a string or list, means to concatenate all
971the elements. This is the most common form of mode line construct.
972
973@item (@var{symbol} @var{then} @var{else})
974A list whose first element is a symbol is a conditional. Its meaning
975depends on the value of @var{symbol}. If the value is non-@code{nil},
976the second element of the list (@var{then}) is processed recursively as
977a mode line element. But if the value of @var{symbol} is @code{nil},
978the third element of the list (if there is one) is processed
979recursively.
980
981@item (@var{width} @var{rest}@dots{})
982A list whose first element is an integer specifies truncation or
983padding of the results of @var{rest}. The remaining elements
984@var{rest} are processed recursively as mode line constructs and
985concatenated together. Then the result is space filled (if
986@var{width} is positive) or truncated (to @minus{}@var{width} columns,
987if @var{width} is negative) on the right.
988
989For example, the usual way to show what percentage of a buffer is above
990the top of the window is to use a list like this: @code{(-3 . "%p")}.
991@end table
992
993 If you do alter @code{mode-line-format} itself, the new value should
994use all the same variables that are used by the default value, rather
995than duplicating their contents or displaying the information in another
996fashion. This way, customizations made by the user, by libraries (such
997as @code{display-time}) and by major modes via changes to those
998variables remain effective.
999
1000@cindex Shell mode @code{mode-line-format}
1001 Here is an example of a @code{mode-line-format} that might be
1002useful for @code{shell-mode} since it contains the hostname and default
1003directory.
1004
1005@example
1006@group
1007(setq mode-line-format
1008 (list ""
1009 'mode-line-modified
1010 "%b--"
1011@end group
1012 (getenv "HOST") ; @r{One element is not constant.}
1013 ":"
1014 'default-directory
1015 " "
1016 'global-mode-string
1017 " %[(" 'mode-name
1018 'minor-mode-alist
1019 "%n"
1020 'mode-line-process
1021 ")%]----"
1022@group
1023 (line-number-mode "L%l--")
1024 '(-3 . "%p")
1025 "-%-"))
1026@end group
1027@end example
1028
1029@node Mode Line Variables
1030@subsection Variables Used in the Mode Line
1031
1032 This section describes variables incorporated by the
1033standard value of @code{mode-line-format} into the text of the mode
1034line. There is nothing inherently special about these variables; any
1035other variables could have the same effects on the mode line if
1036@code{mode-line-format} were changed to use them.
1037
1038@defvar mode-line-modified
1039 This variable holds the value of the mode-line construct that displays
1040whether the current buffer is modified.
1041
1042 The default value of @code{mode-line-modified} is
1043@code{("--%1*%1*-")}. This means that the mode line displays
1044@samp{--**-} if the buffer is modified, @samp{-----} if the buffer is
1045not modified, and @samp{--%%-} if the buffer is read only.
1046
1047Changing this variable does not force an update of the mode line.
1048@end defvar
1049
1050@defvar mode-line-buffer-identification
1051 This variable identifies the buffer being displayed in the window.
1052Its default value is @samp{Emacs: %17b}, which means that it displays
1053@samp{Emacs:} followed by the buffer name. You may want to change this
1054in modes such as Rmail that do not behave like a ``normal'' Emacs.
1055@end defvar
1056
1057@defvar global-mode-string
1058This variable holds a mode line spec that appears in the mode line by
1059default, just after the buffer name. The command @code{display-time}
1060sets @code{global-mode-string} to refer to the variable
1061@code{display-time-string}, which holds a string containing the time and
1062load information.
1063
1064The @samp{%M} construct substitutes the value of
1065@code{global-mode-string}, but this is obsolete, since the variable is
1066included directly in the mode line.
1067@end defvar
1068
1069@defvar mode-name
1070 This buffer-local variable holds the ``pretty'' name of the current
1071buffer's major mode. Each major mode should set this variable so that the
1072mode name will appear in the mode line.
1073@end defvar
1074
1075@defvar minor-mode-alist
1076 This variable holds an association list whose elements specify how the
1077mode line should indicate that a minor mode is active. Each element of
1078the @code{minor-mode-alist} should be a two-element list:
1079
1080@example
1081(@var{minor-mode-variable} @var{mode-line-string})
1082@end example
1083
1084More generally, @var{mode-line-string} can be any mode line spec. It
1085appears in the mode line when the value of @var{minor-mode-variable} is
1086non-@code{nil}, and not otherwise. These strings should begin with
1087spaces so that they don't run together. Conventionally, the
1088@var{minor-mode-variable} for a specific mode is set to a non-@code{nil}
1089value when that minor mode is activated.
1090
1091The default value of @code{minor-mode-alist} is:
1092
1093@example
1094@group
1095minor-mode-alist
1096@result{} ((abbrev-mode " Abbrev")
1097 (overwrite-mode " Ovwrt")
1098 (auto-fill-function " Fill")
1099 (defining-kbd-macro " Def"))
1100@end group
1101@end example
1102
1103@noindent
1104(In earlier Emacs versions, @code{auto-fill-function} was called
1105@code{auto-fill-hook}.)
1106
1107 @code{minor-mode-alist} is not buffer-local. The variables mentioned
1108in the alist should be buffer-local if the minor mode can be enabled
1109separately in each buffer.
1110@end defvar
1111
1112@defvar mode-line-process
1113This buffer-local variable contains the mode line information on process
1114status in modes used for communicating with subprocesses. It is
1115displayed immediately following the major mode name, with no intervening
1116space. For example, its value in the @samp{*shell*} buffer is
1117@code{(":@: %s")}, which allows the shell to display its status along
1118with the major mode as: @samp{(Shell:@: run)}. Normally this variable
1119is @code{nil}.
1120@end defvar
1121
1122@defvar default-mode-line-format
1123 This variable holds the default @code{mode-line-format} for buffers
1124that do not override it. This is the same as @code{(default-value
1125'mode-line-format)}.
1126
1127 The default value of @code{default-mode-line-format} is:
1128
1129@example
1130@group
1131(""
1132 mode-line-modified
1133 mode-line-buffer-identification
1134 " "
1135 global-mode-string
1136 " %[("
1137 mode-name
1138@end group
1139@group
1140 minor-mode-alist
1141 "%n"
1142 mode-line-process
1143 ")%]----"
1144 (-3 . "%p")
1145 "-%-")
1146@end group
1147@end example
1148@end defvar
1149
1150@node %-Constructs
1151@subsection @code{%}-Constructs in the Mode Line
1152
1153 The following table lists the recognized @code{%}-constructs and what
1154they mean.
1155
1156@table @code
1157@item %b
1158The current buffer name, obtained with the @code{buffer-name} function.
1159@xref{Buffer Names}.
1160
1161@item %f
1162The visited file name, obtained with the @code{buffer-file-name}
1163function. @xref{Buffer File Name}.
1164
1165@item %*
1166@samp{%} if the buffer is read only (see @code{buffer-read-only}); @*
1167@samp{*} if the buffer is modified (see @code{buffer-modified-p}); @*
1168@samp{-} otherwise. @xref{Buffer Modification}.
1169
1170@item %+
1171@samp{*} if the buffer is modified, and otherwise @samp{-}.
1172
1173@item %s
1174The status of the subprocess belonging to the current buffer, obtained with
1175@code{process-status}. @xref{Process Information}.
1176
1177@item %p
1178The percent of the buffer above the @strong{top} of window, or
1179@samp{Top}, @samp{Bottom} or @samp{All}.
1180
1181@item %P
1182The percentage of the buffer text that is above the @strong{bottom} of
1183the window (which includes the text visible in the window, as well as
1184the text above the top), plus @samp{Top} if the top of the buffer is
1185visible on screen; or @samp{Bottom} or @samp{All}.
1186
1187@item %n
1188@samp{Narrow} when narrowing is in effect; nothing otherwise (see
1189@code{narrow-to-region} in @ref{Narrowing}).
1190
1191@item %[
1192An indication of the depth of recursive editing levels (not counting
1193minibuffer levels): one @samp{[} for each editing level.
1194@xref{Recursive Editing}.
1195
1196@item %]
1197One @samp{]} for each recursive editing level (not counting minibuffer
1198levels).
1199
1200@item %%
1201The character @samp{%}---this is how to include a literal @samp{%} in a
1202string in which @code{%}-constructs are allowed.
1203
1204@item %-
1205Dashes sufficient to fill the remainder of the mode line.
1206@end table
1207
1208The following two @code{%}-constructs are still supported, but they are
1209obsolete, since you can get the same results with the variables
1210@code{mode-name} and @code{global-mode-string}.
1211
1212@table @code
1213@item %m
1214The value of @code{mode-name}.
1215
1216@item %M
1217The value of @code{global-mode-string}. Currently, only
1218@code{display-time} modifies the value of @code{global-mode-string}.
1219@end table
1220
1221@node Hooks
1222@section Hooks
1223@cindex hooks
1224
1225 A @dfn{hook} is a variable where you can store a function or functions
1226to be called on a particular occasion by an existing program. Emacs
1227provides hooks for the sake of customization. Most often, hooks are set
1228up in the @file{.emacs} file, but Lisp programs can set them also.
1229@xref{Standard Hooks}, for a list of standard hook variables.
1230
1231 Most of the hooks in Emacs are @dfn{normal hooks}. These variables
1232contain lists of functions to be called with no arguments. The reason
1233most hooks are normal hooks is so that you can use them in a uniform
1234way. You can always tell when a hook is a normal hook, because its
1235name ends in @samp{-hook}.
1236
1237 The recommended way to add a hook function to a normal hook is by
1238calling @code{add-hook} (see below). The hook functions may be any of
1239the valid kinds of functions that @code{funcall} accepts (@pxref{What Is
1240a Function}). Most normal hook variables are initially void;
1241@code{add-hook} knows how to deal with this.
1242
1243 As for abnormal hooks, those whose names end in @samp{-function} have
1244a value which is a single function. Those whose names end in
1245@samp{-hooks} have a value which is a list of functions. Any hook which
1246is abnormal is abnormal because a normal hook won't do the job; either
1247the functions are called with arguments, or their values are meaningful.
1248The name shows you that the hook is abnormal and that you should look at
1249its documentation string to see how to use it properly.
1250
1251 Most major modes run hooks as the last step of initialization. This
1252makes it easy for a user to customize the behavior of the mode, by
1253overriding the local variable assignments already made by the mode. But
1254hooks are used in other contexts too. For example, the hook
1255@code{suspend-hook} runs just before Emacs suspends itself
1256(@pxref{Suspending Emacs}).
1257
1258 Here's an expression you can put in your @file{.emacs} file to turn on
1259Auto Fill mode when in Lisp Interaction mode:
1260
1261@example
1262(add-hook 'lisp-interaction-mode-hook 'turn-on-auto-fill)
1263@end example
1264
1265 The next example shows how to use a hook to customize the way Emacs
1266formats C code. (People often have strong personal preferences for one
1267format or another.) Here the hook function is an anonymous lambda
1268expression.
1269
1270@cindex lambda expression in hook
1271@example
1272@group
1273(add-hook 'c-mode-hook
1274 (function (lambda ()
1275 (setq c-indent-level 4
1276 c-argdecl-indent 0
1277 c-label-offset -4
1278@end group
1279@group
1280 c-continued-statement-indent 0
1281 c-brace-offset 0
1282 comment-column 40))))
1283
1284(setq c++-mode-hook c-mode-hook)
1285@end group
1286@end example
1287
1288 Finally, here is an example of how to use the Text mode hook to
1289provide a customized mode line for buffers in Text mode, displaying the
1290default directory in addition to the standard components of the
1291mode line. (This may cause the mode line to run out of space if you
1292have very long file names or display the time and load.)
1293
1294@example
1295@group
1296(add-hook 'text-mode-hook
1297 (function (lambda ()
1298 (setq mode-line-format
1299 '(mode-line-modified
1300 "Emacs: %14b"
1301 " "
1302@end group
1303 default-directory
1304 " "
1305 global-mode-string
1306 "%[("
1307 mode-name
1308 minor-mode-alist
1309@group
1310 "%n"
1311 mode-line-process
1312 ") %]---"
1313 (-3 . "%p")
1314 "-%-")))))
1315@end group
1316@end example
1317
1318 At the appropriate time, Emacs uses the @code{run-hooks} function to
1319run particular hooks. This function calls the hook functions you have
1320added with @code{add-hooks}.
1321
1322@defun run-hooks &rest hookvar
1323This function takes one or more hook variable names as arguments, and
1324runs each hook in turn. Each @var{hookvar} argument should be a symbol
1325that is a hook variable. These arguments are processed in the order
1326specified.
1327
1328If a hook variable has a non-@code{nil} value, that value may be a
1329function or a list of functions. If the value is a function (either a
1330lambda expression or a symbol with a function definition), it is
1331called. If it is a list, the elements are called, in order.
1332The hook functions are called with no arguments.
1333
1334For example, here's how @code{emacs-lisp-hooks} runs its mode hook:
1335
1336@example
1337(run-hooks 'emacs-lisp-mode-hook)
1338@end example
1339@end defun
1340
1341@defun add-hook hook function &optional append
1342This function is the handy way to add function @var{function} to hook
1343variable @var{hook}. For example,
1344
1345@example
1346(add-hook 'text-mode-hook 'my-text-hook-function)
1347@end example
1348
1349@noindent
1350adds @code{my-text-hook-function} to the hook called @code{text-mode-hook}.
1351
1352It is best to design your hook functions so that the order in which they
1353are executed does not matter. Any dependence on the order is ``asking
1354for trouble.'' However, the order is predictable: normally,
1355@var{function} goes at the front of the hook list, so it will be
1356executed first (barring another @code{add-hook} call).
1357
1358If the optional argument @var{append} is non-@code{nil}, the new hook
1359function goes at the end of the hook list and will be executed last.
1360@end defun
1361
1362@defun remove-hook hook function
1363This function removes @var{function} from the hook variable @var{hook}.
1364@end defun