aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorRichard M. Stallman1994-03-28 20:21:44 +0000
committerRichard M. Stallman1994-03-28 20:21:44 +0000
commit73804d4b1beeb0e5510792396018296c672288b2 (patch)
tree419247c40388c0d26bad57523b2c56d933a6a57d
parentf142f62a0ac4d515265edc4fcdda31f0b63a7311 (diff)
downloademacs-73804d4b1beeb0e5510792396018296c672288b2.tar.gz
emacs-73804d4b1beeb0e5510792396018296c672288b2.zip
Initial revision
-rw-r--r--lispref/Makefile.in120
-rw-r--r--lispref/debugging.texi701
-rw-r--r--lispref/edebug.texi1676
-rw-r--r--lispref/eval.texi695
-rw-r--r--lispref/keymaps.texi1638
-rw-r--r--lispref/lists.texi1384
-rw-r--r--lispref/macros.texi593
-rw-r--r--lispref/os.texi1355
-rw-r--r--lispref/processes.texi1139
-rw-r--r--lispref/text.texi2658
10 files changed, 11959 insertions, 0 deletions
diff --git a/lispref/Makefile.in b/lispref/Makefile.in
new file mode 100644
index 00000000000..4a51dcb6cd9
--- /dev/null
+++ b/lispref/Makefile.in
@@ -0,0 +1,120 @@
1# Makefile for the GNU Emacs Lisp Reference Manual.
2#
3# 11 August 1990
4
5# Redefine `TEX' if `tex' does not invoke plain TeX. For example:
6# TEX=platex
7
8TEX=tex
9
10# Where the TeX macros are kept:
11texmacrodir = /usr/local/lib/tex/macros
12
13# Where the Emacs hierarchy lives ($EMACS in the INSTALL document for Emacs.)
14# For example:
15# emacslibdir = /usr/local/gnu/lib/emacs
16
17# Directory where Emacs is installed, by default:
18emacslibdir = /usr/local/emacs
19
20# Unless you have a nonstandard Emacs installation, these shouldn't have to
21# be changed.
22prefix = /usr/local
23infodir = ${prefix}/info
24
25# The name of the manual:
26
27VERSION=2.02.2
28manual = elisp-manual-19-$(VERSION)
29
30# Uncomment this line for permuted index.
31# permuted_index = 1
32
33# List of all the texinfo files in the manual:
34
35srcs = elisp.texi back.texi \
36 abbrevs.texi anti.texi backups.texi locals.texi buffers.texi \
37 calendar.texi commands.texi compile.texi control.texi debugging.texi \
38 display.texi edebug.texi errors.texi eval.texi files.texi \
39 frames.texi functions.texi help.texi hooks.texi \
40 internals.texi intro.texi keymaps.texi lists.texi \
41 loading.texi macros.texi maps.texi markers.texi \
42 minibuf.texi modes.texi numbers.texi objects.texi \
43 os.texi positions.texi processes.texi searching.texi \
44 sequences.texi streams.texi strings.texi symbols.texi \
45 syntax.texi text.texi tips.texi variables.texi \
46 windows.texi \
47 index.unperm index.perm
48
49.PHONY: elisp.dvi clean
50
51elisp.dvi: $(srcs) index.texi texindex
52 # Avoid losing old contents of aux file entirely.
53 -mv elisp.aux elisp.oaux
54 # First shot to define xrefs:
55 $(TEX) elisp.texi
56 if [ a${permuted_index} != a ]; \
57 then \
58 ./permute-index; \
59 mv permuted.fns elisp.fns; \
60 else \
61 ./texindex elisp.??; \
62 fi
63 $(TEX) elisp.texi
64
65index.texi:
66 if [ a${permuted_index} != a ]; \
67 then \
68 ln -s index.perm index.texi; \
69 else \
70 ln -s index.unperm index.texi; \
71 fi
72
73# The info file is named `elisp'.
74
75elisp: $(srcs) index.texi makeinfo
76 ./makeinfo elisp.texi
77
78install: elisp elisp.dvi
79 mv elisp elisp-* $(infodir)
80 @echo also add the line for elisp to $(infodir)/dir.
81
82installall: install
83 install -c texinfo.tex $(texmacrodir)
84
85clean:
86 rm -f *.toc *.aux *.log *.cp *.cps *.fn *.fns *.tp *.tps \
87 *.vr *.vrs *.pg *.pgs *.ky *.kys
88 rm -f make.out core
89 rm -f makeinfo.o makeinfo getopt.o getopt1.o
90 rm -f texindex.o texindex index.texi
91
92dist:
93 -mkdir temp
94 -mkdir temp/$(manual)
95 -ln README Makefile permute-index $(srcs) \
96 texinfo.tex getopt.c getopt1.c getopt.h \
97 elisp.dvi elisp.aux elisp.??s elisp elisp-[0-9] elisp-[0-9][0-9] temp/$(manual)
98 -rm -f temp/$(manual)/texindex.c temp/$(manual)/makeinfo.c
99 cp texindex.c makeinfo.c temp/$(manual)
100 (cd temp/$(manual); rm -f *~)
101 (cd temp; tar chf - $(manual)) | gzip > $(manual).tar.gz
102 -rm -rf temp
103
104# Make two programs used in generating output from texinfo.
105
106CFLAGS = -g
107
108texindex: texindex.o
109 $(CC) -o $@ $(LDFLAGS) $(CFLAGS) $?
110texindex.o: texindex.c
111
112MAKEINFO_MAJOR = 1
113MAKEINFO_MINOR = 0
114MAKEINFO_FLAGS = -DMAKEINFO_MAJOR=$(MAKEINFO_MAJOR) -DMAKEINFO_MINOR=$(MAKEINFO_MINOR)
115
116makeinfo: makeinfo.o getopt.o getopt1.o
117 $(CC) $(LDFLAGS) -o makeinfo makeinfo.o getopt.o getopt1.o
118
119makeinfo.o: makeinfo.c
120 $(CC) -c $(CFLAGS) $(MAKEINFO_FLAGS) makeinfo.c
diff --git a/lispref/debugging.texi b/lispref/debugging.texi
new file mode 100644
index 00000000000..b16c5407c93
--- /dev/null
+++ b/lispref/debugging.texi
@@ -0,0 +1,701 @@
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/debugging
6@node Debugging, Streams, Byte Compilation, Top
7@chapter Debugging Lisp Programs
8
9 There are three ways to investigate a problem in an Emacs Lisp program,
10depending on what you are doing with the program when the problem appears.
11
12@itemize @bullet
13@item
14If the problem occurs when you run the program, you can use a Lisp
15debugger (either the default debugger or Edebug) to investigate what is
16happening during execution.
17
18@item
19If the problem is syntactic, so that Lisp cannot even read the program,
20you can use the Emacs facilities for editing Lisp to localize it.
21
22@item
23If the problem occurs when trying to compile the program with the byte
24compiler, you need to know how to examine the compiler's input buffer.
25@end itemize
26
27@menu
28* Debugger:: How the Emacs Lisp debugger is implemented.
29* Syntax Errors:: How to find syntax errors.
30* Compilation Errors:: How to find errors that show up in byte compilation.
31* Edebug:: A source-level Emacs Lisp debugger.
32@end menu
33
34 Another useful debugging tool is the dribble file. When a dribble
35file is open, Emacs copies all keyboard input characters to that file.
36Afterward, you can examine the file to find out what input was used.
37@xref{Terminal Input}.
38
39 For debugging problems in terminal descriptions, the
40@code{open-termscript} function can be useful. @xref{Terminal Output}.
41
42@node Debugger
43@section The Lisp Debugger
44@cindex debugger
45@cindex Lisp debugger
46@cindex break
47
48 The @dfn{Lisp debugger} provides the ability to suspend evaluation of
49a form. While evaluation is suspended (a state that is commonly known
50as a @dfn{break}), you may examine the run time stack, examine the
51values of local or global variables, or change those values. Since a
52break is a recursive edit, all the usual editing facilities of Emacs are
53available; you can even run programs that will enter the debugger
54recursively. @xref{Recursive Editing}.
55
56@menu
57* Error Debugging:: Entering the debugger when an error happens.
58* Infinite Loops:: Stopping and debugging a program that doesn't exit.
59* Function Debugging:: Entering it when a certain function is called.
60* Explicit Debug:: Entering it at a certain point in the program.
61* Using Debugger:: What the debugger does; what you see while in it.
62* Debugger Commands:: Commands used while in the debugger.
63* Invoking the Debugger:: How to call the function @code{debug}.
64* Internals of Debugger:: Subroutines of the debugger, and global variables.
65@end menu
66
67@node Error Debugging
68@subsection Entering the Debugger on an Error
69@cindex error debugging
70@cindex debugging errors
71
72 The most important time to enter the debugger is when a Lisp error
73happens. This allows you to investigate the immediate causes of the
74error.
75
76 However, entry to the debugger is not a normal consequence of an
77error. Many commands frequently get Lisp errors when invoked in
78inappropriate contexts (such as @kbd{C-f} at the end of the buffer) and
79during ordinary editing it would be very unpleasant to enter the
80debugger each time this happens. If you want errors to enter the
81debugger, set the variable @code{debug-on-error} to non-@code{nil}.
82
83@defopt debug-on-error
84This variable determines whether the debugger is called when a error is
85signaled and not handled. If @code{debug-on-error} is @code{t}, all
86errors call the debugger. If it is @code{nil}, none call the debugger.
87
88The value can also be a list of error conditions that should call the
89debugger. For example, if you set it to the list
90@code{(void-variable)}, then only errors about a variable that has no
91value invoke the debugger.
92@end defopt
93
94 To debug an error that happens during loading of the @file{.emacs}
95file, use the option @samp{-debug-init}, which binds
96@code{debug-on-error} to @code{t} while @file{.emacs} is loaded.
97
98 If your @file{.emacs} file sets @code{debug-on-error}, the effect
99lasts only until the end of loading @file{.emacs}. (This is an
100undesirable by-product of the @samp{-debug-init} feature.) If you want
101@file{.emacs} to set @code{debug-on-error} permanently, use
102@code{after-init-hook}, like this:
103
104@example
105(add-hook 'after-init-hook
106 '(lambda () (setq debug-on-error t)))
107@end example
108
109@node Infinite Loops
110@subsection Debugging Infinite Loops
111@cindex infinite loops
112@cindex loops, infinite
113@cindex quitting from infinite loop
114@cindex stopping an infinite loop
115
116 When a program loops infinitely and fails to return, your first
117problem is to stop the loop. On most operating systems, you can do this
118with @kbd{C-g}, which causes quit.
119
120 Ordinary quitting gives no information about why the program was
121looping. To get more information, you can set the variable
122@code{debug-on-quit} to non-@code{nil}. Quitting with @kbd{C-g} is not
123considered an error, and @code{debug-on-error} has no effect on the
124handling of @kbd{C-g}. Contrariwise, @code{debug-on-quit} has no effect
125on errors.@refill
126
127 Once you have the debugger running in the middle of the infinite loop,
128you can proceed from the debugger using the stepping commands. If you
129step through the entire loop, you will probably get enough information
130to solve the problem.
131
132@defopt debug-on-quit
133This variable determines whether the debugger is called when @code{quit}
134is signaled and not handled. If @code{debug-on-quit} is non-@code{nil},
135then the debugger is called whenever you quit (that is, type @kbd{C-g}).
136If @code{debug-on-quit} is @code{nil}, then the debugger is not called
137when you quit. @xref{Quitting}.
138@end defopt
139
140@node Function Debugging
141@subsection Entering the Debugger on a Function Call
142@cindex function call debugging
143@cindex debugging specific functions
144
145 To investigate a problem that happens in the middle of a program, one
146useful technique is to enter the debugger whenever a certain function is
147called. You can do this to the function in which the problem occurs,
148and then step through the function, or you can do this to a function
149called shortly before the problem, step quickly over the call to that
150function, and then step through its caller.
151
152@deffn Command debug-on-entry function-name
153 This function requests @var{function-name} to invoke the debugger each time
154it is called. It works by inserting the form @code{(debug 'debug)} into
155the function definition as the first form.
156
157 Any function defined as Lisp code may be set to break on entry,
158regardless of whether it is interpreted code or compiled code. If the
159function is a command, it will enter the debugger when called from Lisp
160and when called interactively (after the reading of the arguments). You
161can't debug primitive functions (i.e., those written in C) this way.
162
163 When @code{debug-on-entry} is called interactively, it prompts
164for @var{function-name} in the minibuffer.
165
166 If the function is already set up to invoke the debugger on entry,
167@code{debug-on-entry} does nothing.
168
169 Caveat: if you redefine a function after using @code{debug-on-entry}
170on it, the code to enter the debugger is lost.
171
172 @code{debug-on-entry} returns @var{function-name}.
173
174@example
175@group
176(defun fact (n)
177 (if (zerop n) 1
178 (* n (fact (1- n)))))
179 @result{} fact
180@end group
181@group
182(debug-on-entry 'fact)
183 @result{} fact
184@end group
185@group
186(fact 3)
187 @result{} 6
188@end group
189
190@group
191------ Buffer: *Backtrace* ------
192Entering:
193* fact(3)
194 eval-region(4870 4878 t)
195 byte-code("...")
196 eval-last-sexp(nil)
197 (let ...)
198 eval-insert-last-sexp(nil)
199* call-interactively(eval-insert-last-sexp)
200------ Buffer: *Backtrace* ------
201@end group
202
203@group
204(symbol-function 'fact)
205 @result{} (lambda (n)
206 (debug (quote debug))
207 (if (zerop n) 1 (* n (fact (1- n)))))
208@end group
209@end example
210@end deffn
211
212@deffn Command cancel-debug-on-entry function-name
213This function undoes the effect of @code{debug-on-entry} on
214@var{function-name}. When called interactively, it prompts for
215@var{function-name} in the minibuffer.
216
217If @code{cancel-debug-on-entry} is called more than once on the same
218function, the second call does nothing. @code{cancel-debug-on-entry}
219returns @var{function-name}.
220@end deffn
221
222@node Explicit Debug
223@subsection Explicit Entry to the Debugger
224
225 You can cause the debugger to be called at a certain point in your
226program by writing the expression @code{(debug)} at that point. To do
227this, visit the source file, insert the text @samp{(debug)} at the
228proper place, and type @kbd{C-M-x}. Be sure to undo this insertion
229before you save the file!
230
231 The place where you insert @samp{(debug)} must be a place where an
232additional form can be evaluated and its value ignored. (If the value
233isn't ignored, it will alter the execution of the program!) The most
234common suitable places are inside a @code{progn} or an implicit
235@code{progn} (@pxref{Sequencing}).
236
237@node Using Debugger
238@subsection Using the Debugger
239
240 When the debugger is entered, it displays the previously selected
241buffer in one window and a buffer named @samp{*Backtrace*} in another
242window. The backtrace buffer contains one line for each level of Lisp
243function execution currently going on. At the beginning of this buffer
244is a message describing the reason that the debugger was invoked (such
245as the error message and associated data, if it was invoked due to an
246error).
247
248 The backtrace buffer is read-only and uses a special major mode,
249Debugger mode, in which letters are defined as debugger commands. The
250usual Emacs editing commands are available; thus, you can switch windows
251to examine the buffer that was being edited at the time of the error,
252switch buffers, visit files, or do any other sort of editing. However,
253the debugger is a recursive editing level (@pxref{Recursive Editing})
254and it is wise to go back to the backtrace buffer and exit the debugger
255(with the @kbd{q} command) when you are finished with it. Exiting
256the debugger gets out of the recursive edit and kills the backtrace
257buffer.
258
259@cindex current stack frame
260 The contents of the backtrace buffer show you the functions that are
261executing and their argument values. It also allows you to specify a
262stack frame by moving point to the line describing that frame. (A stack
263frame is the place where the Lisp interpreter records information about
264a particular invocation of a function.) The frame whose line point is
265on is considered the @dfn{current frame}. Some of the debugger commands
266operate on the current frame.
267
268 The debugger itself must be run byte-compiled, since it makes
269assumptions about how many stack frames are used for the debugger
270itself. These assumptions are false if the debugger is running
271interpreted.
272
273@need 3000
274
275@node Debugger Commands
276@subsection Debugger Commands
277@cindex debugger command list
278
279 Inside the debugger (in Debugger mode), these special commands are
280available in addition to the usual cursor motion commands. (Keep in
281mind that all the usual facilities of Emacs, such as switching windows
282or buffers, are still available.)
283
284 The most important use of debugger commands is for stepping through
285code, so that you can see how control flows. The debugger can step
286through the control structures of an interpreted function, but cannot do
287so in a byte-compiled function. If you would like to step through a
288byte-compiled function, replace it with an interpreted definition of the
289same function. (To do this, visit the source file for the function and
290type @kbd{C-M-x} on its definition.)
291
292 Here is a list of Debugger mode commands:
293
294@table @kbd
295@item c
296Exit the debugger and continue execution. When continuing is possible,
297it resumes execution of the program as if the debugger had never been
298entered (aside from the effect of any variables or data structures you
299may have changed while inside the debugger).
300
301Continuing is possible after entry to the debugger due to function entry
302or exit, explicit invocation, or quitting. You cannot continue if the
303debugger was entered because of an error.
304
305@item d
306Continue execution, but enter the debugger the next time any Lisp
307function is called. This allows you to step through the
308subexpressions of an expression, seeing what values the subexpressions
309compute, and what else they do.
310
311The stack frame made for the function call which enters the debugger in
312this way will be flagged automatically so that the debugger will be
313called again when the frame is exited. You can use the @kbd{u} command
314to cancel this flag.
315
316@item b
317Flag the current frame so that the debugger will be entered when the
318frame is exited. Frames flagged in this way are marked with stars
319in the backtrace buffer.
320
321@item u
322Don't enter the debugger when the current frame is exited. This
323cancels a @kbd{b} command on that frame.
324
325@item e
326Read a Lisp expression in the minibuffer, evaluate it, and print the
327value in the echo area. The debugger alters certain important variables
328as part of its operation; @kbd{e} temporarily restores their
329outside-the-debugger values so you can examine them. This makes the
330debugger more transparent. By contrast, @kbd{M-@key{ESC}} does nothing
331special in the debugger; it shows you the variable values within the
332debugger.
333
334@item q
335Terminate the program being debugged; return to top-level Emacs
336command execution.
337
338If the debugger was entered due to a @kbd{C-g} but you really want
339to quit, and not debug, use the @kbd{q} command.
340
341@item r
342Return a value from the debugger. The value is computed by reading an
343expression with the minibuffer and evaluating it.
344
345The @kbd{r} command makes a difference when the debugger was invoked due
346to exit from a Lisp call frame (as requested with @kbd{b}); then the
347value specified in the @kbd{r} command is used as the value of that
348frame.
349
350You can't use @kbd{r} when the debugger was entered due to an error.
351@end table
352
353@node Invoking the Debugger
354@subsection Invoking the Debugger
355
356 Here we describe fully the function used to invoke the debugger.
357
358@defun debug &rest debugger-args
359This function enters the debugger. It switches buffers to a buffer
360named @samp{*Backtrace*} (or @samp{*Backtrace*<2>} if it is the second
361recursive entry to the debugger, etc.), and fills it with information
362about the stack of Lisp function calls. It then enters a recursive
363edit, showing the backtrace buffer in Debugger mode.
364
365The Debugger mode @kbd{c} and @kbd{r} commands exit the recursive edit;
366then @code{debug} switches back to the previous buffer and returns to
367whatever called @code{debug}. This is the only way the function
368@code{debug} can return to its caller.
369
370If the first of the @var{debugger-args} passed to @code{debug} is
371@code{nil} (or if it is not one of the special values in the table
372below), then @code{debeg} displays the rest of its arguments at the the
373top of the @samp{*Backtrace*} buffer. This mechanism is used to display
374a message to the user.
375
376However, if the first argument passed to @code{debug} is one of the
377following special values, then it has special significance. Normally,
378these values are passed to @code{debug} only by the internals of Emacs
379and the debugger, and not by programmers calling @code{debug}.
380
381The special values are:
382
383@table @code
384@item lambda
385@cindex @code{lambda} in debug
386A first argument of @code{lambda} means @code{debug} was called because
387of entry to a function when @code{debug-on-next-call} was
388non-@code{nil}. The debugger displays @samp{Entering:} as a line of
389text at the top of the buffer.
390
391@item debug
392@code{debug} as first argument indicates a call to @code{debug} because
393of entry to a function that was set to debug on entry. The debugger
394displays @samp{Entering:}, just as in the @code{lambda} case. It also
395marks the stack frame for that function so that it will invoke the
396debugger when exited.
397
398@item t
399When the first argument is @code{t}, this indicates a call to
400@code{debug} due to evaluation of a list form when
401@code{debug-on-next-call} is non-@code{nil}. The debugger displays the
402following as the top line in the buffer:
403
404@smallexample
405Beginning evaluation of function call form:
406@end smallexample
407
408@item exit
409When the first argument is @code{exit}, it indicates the exit of a
410stack frame previously marked to invoke the debugger on exit. The
411second argument given to @code{debug} in this case is the value being
412returned from the frame. The debugger displays @samp{Return value:} on
413the top line of the buffer, followed by the value being returned.
414
415@item error
416@cindex @code{error} in debug
417When the first argument is @code{error}, the debugger indicates that
418it is being entered because an error or @code{quit} was signaled and not
419handled, by displaying @samp{Signaling:} followed by the error signaled
420and any arguments to @code{signal}. For example,
421
422@example
423@group
424(let ((debug-on-error t))
425 (/ 1 0))
426@end group
427
428@group
429------ Buffer: *Backtrace* ------
430Signaling: (arith-error)
431 /(1 0)
432...
433------ Buffer: *Backtrace* ------
434@end group
435@end example
436
437If an error was signaled, presumably the variable
438@code{debug-on-error} is non-@code{nil}. If @code{quit} was signaled,
439then presumably the variable @code{debug-on-quit} is non-@code{nil}.
440
441@item nil
442Use @code{nil} as the first of the @var{debugger-args} when you want
443to enter the debugger explicitly. The rest of the @var{debugger-args}
444are printed on the top line of the buffer. You can use this feature to
445display messages---for example, to remind yourself of the conditions
446under which @code{debug} is called.
447@end table
448@end defun
449
450@need 5000
451
452@node Internals of Debugger
453@subsection Internals of the Debugger
454
455 This section describes functions and variables used internally by the
456debugger.
457
458@defvar debugger
459The value of this variable is the function to call to invoke the
460debugger. Its value must be a function of any number of arguments (or,
461more typically, the name of a function). Presumably this function will
462enter some kind of debugger. The default value of the variable is
463@code{debug}.
464
465The first argument that Lisp hands to the function indicates why it
466was called. The convention for arguments is detailed in the description
467of @code{debug}.
468@end defvar
469
470@deffn Command backtrace
471@cindex run time stack
472@cindex call stack
473This function prints a trace of Lisp function calls currently active.
474This is the function used by @code{debug} to fill up the
475@samp{*Backtrace*} buffer. It is written in C, since it must have access
476to the stack to determine which function calls are active. The return
477value is always @code{nil}.
478
479In the following example, a Lisp expression calls @code{backtrace}
480explicitly. This prints the backtrace to the stream
481@code{standard-output}: in this case, to the buffer
482@samp{backtrace-output}. Each line of the backtrace represents one
483function call. The line shows the values of the function's arguments if
484they are all known. If they are still being computed, the line says so.
485The arguments of special forms are elided.
486
487@smallexample
488@group
489(with-output-to-temp-buffer "backtrace-output"
490 (let ((var 1))
491 (save-excursion
492 (setq var (eval '(progn
493 (1+ var)
494 (list 'testing (backtrace))))))))
495
496 @result{} nil
497@end group
498
499@group
500----------- Buffer: backtrace-output ------------
501 backtrace()
502 (list ...computing arguments...)
503 (progn ...)
504 eval((progn (1+ var) (list (quote testing) (backtrace))))
505 (setq ...)
506 (save-excursion ...)
507 (let ...)
508 (with-output-to-temp-buffer ...)
509 eval-region(1973 2142 #<buffer *scratch*>)
510 byte-code("... for eval-print-last-sexp ...")
511 eval-print-last-sexp(nil)
512* call-interactively(eval-print-last-sexp)
513----------- Buffer: backtrace-output ------------
514@end group
515@end smallexample
516
517The character @samp{*} indicates a frame whose debug-on-exit flag is
518set.
519@end deffn
520
521@ignore @c Not worth mentioning
522@defopt stack-trace-on-error
523@cindex stack trace
524This variable controls whether Lisp automatically displays a
525backtrace buffer after every error that is not handled. A quit signal
526counts as an error for this variable. If it is non-@code{nil} then a
527backtrace is shown in a pop-up buffer named @samp{*Backtrace*} on every
528error. If it is @code{nil}, then a backtrace is not shown.
529
530When a backtrace is shown, that buffer is not selected. If either
531@code{debug-on-quit} or @code{debug-on-error} is also non-@code{nil}, then
532a backtrace is shown in one buffer, and the debugger is popped up in
533another buffer with its own backtrace.
534
535We consider this feature to be obsolete and superseded by the debugger
536itself.
537@end defopt
538@end ignore
539
540@defvar debug-on-next-call
541@cindex @code{eval}, and debugging
542@cindex @code{apply}, and debugging
543@cindex @code{funcall}, and debugging
544If this variable is non-@code{nil}, it says to call the debugger before
545the next @code{eval}, @code{apply} or @code{funcall}. Entering the
546debugger sets @code{debug-on-next-call} to @code{nil}.
547
548The @kbd{d} command in the debugger works by setting this variable.
549@end defvar
550
551@defun backtrace-debug level flag
552This function sets the debug-on-exit flag of the stack frame @var{level}
553levels, giving it the value @var{flag}. If @var{flag} is
554non-@code{nil}, this will cause the debugger to be entered when that
555frame later exits. Even a nonlocal exit through that frame will enter
556the debugger.
557
558Normally, this function is only called by the debugger.
559@end defun
560
561@defvar command-debug-status
562This variable records the debugging status of current interactive
563command. Each time a command is called interactively, this variable is
564bound to @code{nil}. The debugger can set this variable to leave
565information for future debugger invocations during the same command.
566
567The advantage of using this variable rather that defining another global
568variable is that the data will never carry over to a subsequent command
569invocation.
570@end defvar
571
572@defun backtrace-frame frame-number
573The function @code{backtrace-frame} is intended for use in Lisp
574debuggers. It returns information about what computation is happening
575in the stack frame @var{frame-number} levels down.
576
577If that frame has not evaluated the arguments yet (or is a special
578form), the value is @code{(nil @var{function} @var{arg-forms}@dots{})}.
579
580If that frame has evaluated its arguments and called its function
581already, the value is @code{(t @var{function}
582@var{arg-values}@dots{})}.
583
584In the return value, @var{function} is whatever was supplied as @sc{car}
585of evaluated list, or a @code{lambda} expression in the case of a macro
586call. If the function has a @code{&rest} argument, that is represented
587as the tail of the list @var{arg-values}.
588
589If the argument is out of range, @code{backtrace-frame} returns
590@code{nil}.
591@end defun
592
593@node Syntax Errors
594@section Debugging Invalid Lisp Syntax
595
596 The Lisp reader reports invalid syntax, but cannot say where the real
597problem is. For example, the error ``End of file during parsing'' in
598evaluating an expression indicates an excess of open parentheses (or
599square brackets). The reader detects this imbalance at the end of the
600file, but it cannot figure out where the close parenthesis should have
601been. Likewise, ``Invalid read syntax: ")"'' indicates an excess close
602parenthesis or missing open parenthesis, but does not say where the
603missing parenthesis belongs. How, then, to find what to change?
604
605 If the problem is not simply an imbalance of parentheses, a useful
606technique is to try @kbd{C-M-e} at the beginning of each defun, and see
607if it goes to the place where that defun appears to end. If it does
608not, there is a problem in that defun.
609
610 However, unmatched parentheses are the most common syntax errors in
611Lisp, and we can give further advice for those cases.
612
613@menu
614* Excess Open:: How to find a spurious open paren or missing close.
615* Excess Close:: How to find a spurious close paren or missing open.
616@end menu
617
618@node Excess Open
619@subsection Excess Open Parentheses
620
621 The first step is to find the defun that is unbalanced. If there is
622an excess open parenthesis, the way to do this is to insert a
623close parenthesis at the end of the file and type @kbd{C-M-b}
624(@code{backward-sexp}). This will move you to the beginning of the
625defun that is unbalanced. (Then type @kbd{C-@key{SPC} C-_ C-u
626C-@key{SPC}} to set the mark there, undo the insertion of the
627close parenthesis, and finally return to the mark.)
628
629 The next step is to determine precisely what is wrong. There is no
630way to be sure of this except to study the program, but often the
631existing indentation is a clue to where the parentheses should have
632been. The easiest way to use this clue is to reindent with @kbd{C-M-q}
633and see what moves.
634
635 Before you do this, make sure the defun has enough close parentheses.
636Otherwise, @kbd{C-M-q} will get an error, or will reindent all the rest
637of the file until the end. So move to the end of the defun and insert a
638close parenthesis there. Don't use @kbd{C-M-e} to move there, since
639that too will fail to work until the defun is balanced.
640
641 Now you can go to the beginning of the defun and type @kbd{C-M-q}.
642Usually all the lines from a certain point to the end of the function
643will shift to the right. There is probably a missing close parenthesis,
644or a superfluous open parenthesis, near that point. (However, don't
645assume this is true; study the code to make sure.) Once you have found
646the discrepancy, undo the @kbd{C-M-q}, since the old indentation is
647probably appropriate to the intended parentheses.
648
649 After you think you have fixed the problem, use @kbd{C-M-q} again. If
650the old indentation actually fit the intended nesting of parentheses,
651and you have put back those parentheses, @kbd{C-M-q} should not change
652anything.
653
654@node Excess Close
655@subsection Excess Close Parentheses
656
657 To deal with an excess close parenthesis, first insert an
658open parenthesis at the beginning of the file and type @kbd{C-M-f} to
659find the end of the unbalanced defun. (Then type @kbd{C-@key{SPC} C-_
660C-u C-@key{SPC}} to set the mark there, undo the insertion of the
661open parenthesis, and finally return to the mark.)
662
663 Then find the actual matching close parenthesis by typing @kbd{C-M-f}
664at the beginning of the defun. This will leave you somewhere short of
665the place where the defun ought to end. It is possible that you will
666find a spurious close parenthesis in that vicinity.
667
668 If you don't see a problem at that point, the next thing to do is to
669type @kbd{C-M-q} at the beginning of the defun. A range of lines will
670probably shift left; if so, the missing open parenthesis or spurious
671close parenthesis is probably near the first of those lines. (However,
672don't assume this is true; study the code to make sure.) Once you have
673found the discrepancy, undo the @kbd{C-M-q}, since the old indentation
674is probably appropriate to the intended parentheses.
675
676@node Compilation Errors
677@section Debugging Problems in Compilation
678
679 When an error happens during byte compilation, it is normally due to
680invalid syntax in the program you are compiling. The compiler prints a
681suitable error message in the @samp{*Compile-Log*} buffer, and then
682stops. The message may state a function name in which the error was
683found, or it may not. Either way, here is how to find out where in the
684file the error occurred.
685
686 What you should do is switch to the buffer @w{@samp{ *Compiler Input*}}.
687(Note that the buffer name starts with a space, so it does not show
688up in @kbd{M-x list-buffers}.) This buffer contains the program being
689compiled, and point shows how far the byte compiler was able to read.
690
691 If the error was due to invalid Lisp syntax, point shows exactly where
692the invalid syntax was @emph{detected}. The cause of the error is not
693necessarily near by! Use the techniques in the previous section to find
694the error.
695
696 If the error was detected while compiling a form that had been read
697successfully, then point is located at the end of the form. In this
698case, it can't localize the error precisely, but can still show you
699which function to check.
700
701@include edebug.texi
diff --git a/lispref/edebug.texi b/lispref/edebug.texi
new file mode 100644
index 00000000000..c36ac42768e
--- /dev/null
+++ b/lispref/edebug.texi
@@ -0,0 +1,1676 @@
1@comment -*-texinfo-*-
2
3@c This file is intended to be used as a section within the Emacs Lisp
4@c Reference Manual. It may also be used by an independent Edebug User
5@c Manual, edebug.tex, in which case the Edebug node below should be used
6@c with the following links to the Bugs section and to the top level:
7
8@c , Bugs and Todo List, Top, Top
9
10@node Edebug, Bugs and Todo List, Top, Top
11@section Edebug
12@cindex Edebug mode
13
14@cindex Edebug
15 Edebug is a source-level debugger for Emacs Lisp programs with which
16you can:
17
18@itemize @bullet
19@item
20Step through evaluation, stopping before and after each expression.
21
22@item
23Set conditional or unconditional breakpoints.
24
25@item
26Stop when a specified condition is true (the global break event).
27
28@item
29Trace slow or fast, stopping briefly at each stop point, or
30at each breakpoint.
31
32@item
33Display expression results and evaluate expressions as if outside of
34Edebug.
35
36@item
37Automatically reevaluate a list of expressions and
38display their results each time Edebug updates the display.
39
40@item
41Output trace info on function enter and exit.
42
43@item
44Stop when an error occurs.
45
46@item
47Display a backtrace, omitting Edebug's own frames.
48
49@item
50Specify argument evaluation for macros and defining forms.
51
52@item
53Obtain rudimentary coverage testing and frequency counts.
54@end itemize
55
56The first three sections below should tell you enough about Edebug to
57enable you to use it.
58
59@menu
60* Using Edebug:: Introduction to use of Edebug.
61* Instrumenting:: You must instrument your code
62 in order to debug it with Edebug.
63* Modes: Edebug Execution Modes. Execution modes, stopping more or less often.
64* Jumping:: Commands to jump to a specified place.
65* Misc: Edebug Misc. Miscellaneous commands.
66* Breakpoints:: Setting breakpoints to make the program stop.
67* Trapping Errors:: trapping errors with Edebug.
68* Views: Edebug Views. Views inside and outside of Edebug.
69* Eval: Edebug Eval. Evaluating expressions within Edebug.
70* Eval List:: Expressions whose values are displayed
71 each time you enter Edebug.
72* Printing in Edebug:: Customization of printing.
73* Trace Buffer:: How to produce trace output in a buffer.
74* Coverage Testing:: How to test evaluation coverage.
75* The Outside Context:: Data that Edebug saves and restores.
76* Instrumenting Macro Calls:: Specifying how to handle macro calls.
77* Options: Edebug Options. Option variables for customizing Edebug.
78@end menu
79
80@node Using Edebug
81@subsection Using Edebug
82
83 To debug a Lisp program with Edebug, you must first @dfn{instrument}
84the Lisp code that you want to debug. A simple way to do this is to
85first move point into the definition of a function or macro and then do
86@kbd{C-u C-M-x} (@code{eval-defun} with a prefix argument). See
87@ref{Instrumenting}, for alternative ways to instrument code.
88
89 Once a function is instrumented, any call to the function activates
90Edebug. Activating Edebug may stop execution and let you step through
91the function, or it may update the display and continue execution while
92checking for debugging commands, depending on which Edebug execution
93mode you have selected. The default execution mode is step, which does
94stop execution. @xref{Edebug Execution Modes}.
95
96 Within Edebug, you normally view an Emacs buffer showing the source of
97the Lisp code you are debugging. This is referred to as the @dfn{source
98code buffer}. This buffer is temporarily read-only.
99
100 An arrow at the left margin indicates the line where the function is
101executing. Point initially shows where within the line the function is
102executing, but this ceases to be true if you move point yourself.
103
104 If you instrument the definition of @code{fac} (shown below) and then
105execute @code{(fac 3)}, here is what you normally see. Point is at the
106open-parenthesis before @code{if}.
107
108@example
109(defun fac (n)
110=>@point{}(if (< 0 n)
111 (* n (fac (1- n)))
112 1))
113@end example
114
115@cindex stop points
116The places within a function where Edebug can stop execution are called
117@dfn{stop points}. These occur both before and after each subexpression
118that is a list, and also after each variable reference.
119Here we show with periods the stop points found in the function
120@code{fac}:
121
122@example
123(defun fac (n)
124 .(if .(< 0 n.).
125 .(* n. .(fac (1- n.).).).
126 1).)
127@end example
128
129The special commands of Edebug are available in the source code buffer
130in addition to the commands of Emacs Lisp mode. For example, you can
131type the Edebug command @key{SPC} to execute until the next stop point.
132If you type @key{SPC} once after entry to @code{fac}, here is the
133display you will see:
134
135@example
136(defun fac (n)
137=>(if @point{}(< 0 n)
138 (* n (fac (1- n)))
139 1))
140@end example
141
142When Edebug stops execution after an expression, it displays the
143expression's value in the echo area.
144
145Other frequently used commands are @kbd{b} to set a breakpoint at a stop
146point, @kbd{g} to execute until a breakpoint is reached, and @kbd{q} to
147exit Edebug and return to the top-level command loop. Type @kbd{?} to
148display a list of all Edebug commands.
149
150@node Instrumenting
151@subsection Instrumenting for Edebug
152
153 In order to use Edebug to debug Lisp code, you must first
154@dfn{instrument} the code. Instrumenting code inserts additional code
155into it, code which invokes Edebug at the proper places.
156
157 Once a function is instrumented, any call to the function activates
158Edebug. This may or may not stop execution, depending on the Edebug
159execution mode in use. Some Edebug modes only update the display to
160indicate the progress of the evaluation without stopping execution.
161
162@kindex C-M-x
163@findex eval-defun (Edebug)
164 Once you have loaded Edebug, the command @kbd{C-M-x}
165(@code{eval-defun}) is redefined so that when invoked with a prefix
166argument on a definition, it instruments the definition before
167evaluating it. (The source code itself is not modified.) If the
168variable @code{edebug-all-defs} is non-@code{nil}, that inverts the
169meaning of the prefix argument: then @kbd{C-M-x} instruments the
170definition @emph{unless} it has a prefix argument. The default value of
171@code{edebug-all-defs} is @code{nil}. The command @kbd{M-x
172edebug-all-defs} toggles the value of the variable
173@code{edebug-all-defs}.
174
175@findex edebug-all-forms
176@findex eval-region (Edebug)
177@findex eval-current-buffer (Edebug)
178 If @code{edebug-all-defs} is non-@code{nil}, then the commands
179@code{eval-region}, @code{eval-current-buffer}, and @code{eval-buffer}
180also instrument any definitions they evaluate. Similarly,
181@code{edebug-all-forms} controls whether @code{eval-region} should
182instrument @emph{any} form, even non-defining forms. This doesn't apply
183to loading or evaluations in the minibuffer. The command @kbd{M-x
184edebug-all-forms} toggles this option.
185
186@findex edebug-eval-top-level-form
187Another command, @kbd{M-x edebug-eval-top-level-form}, is available to
188instrument any top-level form regardless of the value of
189@code{edebug-all-defs} or @code{edebug-all-forms}.
190
191When Edebug is about to instrument code for the first time in a session,
192it runs the hook @code{edebug-setup-hook}, then sets it to @code{nil}.
193You can use this to load up Edebug specifications associated with a
194package you are using, but only when you also use Edebug.
195
196While Edebug is active, the command @kbd{I}
197(@code{edebug-instrument-callee}) instruments the definition of the
198function or macro called by the list form after point, if is not already
199instrumented. This is possible only if Edebug knows where to find the
200source for that function; after loading Edebug, @code{eval-region}
201records the position of every definition it evaluates, even if not
202instrumenting it. See also the @kbd{i} command (@pxref{Jumping}), which
203steps into the call after instrumenting the function.
204
205@cindex special forms (Edebug)
206@cindex interactive commands (Edebug)
207@cindex anonymous lambda expressions (Edebug)
208@cindex Common Lisp (Edebug)
209@pindex cl.el (Edebug)
210@pindex cl-specs.el
211 Edebug knows how to instrument all the standard special forms, an
212interactive form with an expression argument, anonymous lambda
213expressions, and other defining forms. Edebug cannot know what a
214user-defined macro will do with the arguments of a macro call, so you
215must tell it; @xref{Instrumenting Macro Calls}, for details.
216
217@findex eval-expression (Edebug)
218 To remove instrumentation from a definition, simply reevaluate its
219definition in a way that does not instrument. There are two ways of
220evaluating forms without instrumenting them: from a file with
221@code{load}, and from the minibuffer with @code{eval-expression}
222(@kbd{M-ESC}).
223
224 If Edebug detects a syntax error while instrumenting, it leaves point
225at the erroneous code and signals an @code{invalid-read-syntax} error.
226
227 @xref{Edebug Eval}, for other evaluation functions available
228inside of Edebug.
229
230@node Edebug Execution Modes
231@subsection Edebug Execution Modes
232
233@cindex Edebug execution modes
234Edebug supports several execution modes for running the program you are
235debugging. We call these alternatives @dfn{Edebug execution modes}; do
236not confuse them with major or minor modes. The current Edebug mode
237determines how far Edebug continues execution before stopping---whether
238it stops at each stop point, or continues to the next breakpoint, for
239example---and how much Edebug displays the progress of the evaluation
240before it stops.
241
242Normally, you specify the Edebug execution mode by typing a command to
243continue the program in a certain mode. Here is a table of these
244commands. All except for @kbd{S} resume execution of the program, at
245least for a certain distance.
246
247@table @kbd
248@item S
249Stop: don't execute any more of the program for now, just wait for more
250Edebug commands (@code{edebug-stop}).
251
252@item @key{SPC}
253Step: stop at the next stop point encountered (@code{edebug-step-mode}).
254
255@item n
256Next: stop at the next stop point encountered after an expression
257(@code{edebug-next-mode}). Also see @code{edebug-forward-sexp} in
258@ref{Edebug Misc}.
259
260@item t
261Trace: pause one second at each Edebug stop point (@code{edebug-trace-mode}).
262
263@item T
264Rapid trace: update the display at each stop point, but don't actually
265pause (@code{edebug-Trace-fast-mode}).
266
267@item g
268Go: run until the next breakpoint (@code{edebug-go-mode}). @xref{Breakpoints}.
269
270@item c
271Continue: pause one second at each breakpoint, and then continue
272(@code{edebug-continue-mode}).
273
274@item C
275Rapid continue: move point to each breakpoint, but don't pause
276(@code{edebug-Continue-fast-mode}).
277
278@item G
279Go non-stop: ignore breakpoints (@code{edebug-Go-nonstop-mode}). You
280can still stop the program by typing @kbd{S}, or any editing command.
281@end table
282
283In general, the execution modes earlier in the above list run the
284program more slowly or stop sooner.
285
286While executing or tracing, you can interrupt the execution by typing
287any Edebug command. Edebug stops the program at the next stop point and
288then executes the command that you typed. For example, typing @kbd{t}
289during execution switches to trace mode at the next stop point. You can
290use @kbd{S} to stop execution without doing anything else.
291
292If your function happens to read input, a character you type intending
293to interrupt execution may be read by the function instead. You can
294avoid such unintended results by paying attention to when your program
295wants input.
296
297@cindex keyboard macros (Edebug)
298Keyboard macros containing the commands in this section do not
299completely work: exiting from Edebug, to resume the program, loses track
300of the keyboard macro. This is not easy to fix. Also, defining or
301executing a keyboard macro outside of Edebug does not affect commands
302inside Edebug. This is usually an advantage. But see the
303@code{edebug-continue-kbd-macro} option (@pxref{Edebug Options}).
304
305When you enter a new Edebug level, the initial execution mode comes from
306the value of the variable @code{edebug-initial-mode}. By default, this
307specifies step mode. Note that you may reenter the same Edebug level
308several times if, for example, an instrumented function is called
309several times from one command.
310
311
312@node Jumping
313@subsection Jumping
314
315 The commands described in this section execute until they reach a
316specified location. All except @kbd{i} make a temporary breakpoint to
317establish the place to stop, then switch to go mode. Any other
318breakpoint reached before the intended stop point will also stop
319execution. @xref{Breakpoints}, for the details on breakpoints.
320
321 These commands may fail to work as expected in case of nonlocal exit,
322because a nonlocal exit can bypass the temporary breakpoint where you
323expected the program to stop.
324
325@table @kbd
326@item h
327Proceed to the stop point near where point is (@code{edebug-goto-here}).
328
329@item f
330Run the program forward over one expression
331(@code{edebug-forward-sexp}).
332
333@item o
334Run the program until the end of the containing sexp.
335
336@item i
337Step into the function or macro called by the form after point.
338@end table
339
340The @kbd{h} command proceeds to the stop point near the current location
341if point, using a temporary breakpoint. See @ref{Breakpoints}, for more
342about breakpoints.
343
344The @kbd{f} command runs the program forward over one expression. More
345precisely, it sets a temporary breakpoint at the position that
346@kbd{C-M-f} would reach, then executes in go mode so that the program
347will stop at breakpoints.
348
349With a prefix argument @var{n}, the temporary breakpoint is placed
350@var{n} sexps beyond point. If the containing list ends before @var{n}
351more elements, then the place to stop is after the containing
352expression.
353
354Be careful that the position @kbd{C-M-f} finds is a place that the
355program will really get to; this may not be true in a
356@code{cond}, for example.
357
358The @kbd{f} command does @code{forward-sexp} starting at point, rather
359than at the stop point, for flexibility. If you want to execute one
360expression @emph{from the current stop point}, type @kbd{w} first, to
361move point there, and then type @kbd{f}.
362
363The @kbd{o} command continues ``out of'' an expression. It places a
364temporary breakpoint at the end of the sexp containing point. If the
365containing sexp is a function definition itself, it continues until just
366before the last sexp in the definition. If that is where you are now,
367it returns from the function and then stops. In other words, this
368command does not exit the currently executing function unless you are
369positioned after the last sexp.
370
371The @kbd{i} command steps into the function or macro called by the list
372form after point. Note that the form need not be the one about to be
373evaluated. But if the form is a function call about to be evaluated,
374remember to use this command before any of the arguments are evaluated,
375since otherwise it will be too late.
376
377The @kbd{i} command instruments the function or macro it's supposed to
378step into, if it isn't instrumented already. This is convenient, but keep
379in mind that the function or macro remains instrumented unless you explicitly
380arrange to deinstrument it.
381
382@node Edebug Misc
383@subsection Miscellaneous Edebug Commands
384
385 Some miscellaneous Edebug commands are described here.
386
387@table @kbd
388@item ?
389Display the help message for Edebug (@code{edebug-help}).
390
391@item C-]
392Abort one level back to the previous command level
393(@code{abort-recursive-edit}).
394
395@item q
396Return to the top level editor command loop (@code{top-level}). This
397exits all recursive editing levels, including all levels of Edebug
398activity. However, instrumented code protected with
399@code{unwind-protect} or @code{condition-case} forms may resume
400debugging.
401
402@item Q
403Like @kbd{q} but don't stop even for protected code
404(@code{top-level-nonstop}).
405
406@item r
407Redisplay the most recently known expression result in the echo area
408(@code{edebug-previous-result}).
409
410@item d
411Display a backtrace, excluding Edebug's own functions for clarity
412(@code{edebug-backtrace}).
413
414You cannot use debugger commands in the backtrace buffer in Edebug as
415you would in the standard debugger.
416
417The backtrace buffer is killed automatically when you continue
418execution.
419@end table
420
421>From the Edebug recursive edit, you may invoke commands that activate
422Edebug again recursively. Any time Edebug is active, you can quit to
423the top level with @kbd{q} or abort one recursive edit level with
424@kbd{C-]}. You can display a backtrace of all the
425pending evaluations with @kbd{d}.
426
427@node Breakpoints
428@subsection Breakpoints
429
430@cindex breakpoints
431Edebug's step mode stops execution at the next stop point reached.
432There are three other ways to stop Edebug execution once it has started:
433breakpoints, the global break condition, and source breakpoints.
434
435While using Edebug, you can specify @dfn{breakpoints} in the program you
436are testing: points where execution should stop. You can set a
437breakpoint at any stop point, as defined in @ref{Using Edebug}. For
438setting and unsetting breakpoints, the stop point that is affected is
439the first one at or after point in the source code buffer. Here are the
440Edebug commands for breakpoints:
441
442@table @kbd
443@item b
444Set a breakpoint at the stop point at or after point
445(@code{edebug-set-breakpoint}). If you use a prefix argument, the
446breakpoint is temporary (it turns off the first time it stops the
447program).
448
449@item u
450Unset the breakpoint (if any) at the stop point at or after
451point (@code{edebug-unset-breakpoint}).
452
453@item x @var{condition} @key{RET}
454Set a conditional breakpoint which stops the program only if
455@var{condition} evaluates to a non-@code{nil} value
456(@code{edebug-set-conditional-breakpoint}). With a prefix argument, the
457breakpoint is temporary.
458
459@item B
460Move point to the next breakpoint in the definition
461(@code{edebug-next-breakpoint}).
462@end table
463
464While in Edebug, you can set a breakpoint with @kbd{b} and unset one
465with @kbd{u}. First move point to the Edebug stop point of your choice,
466then type @kbd{b} or @kbd{u} to set or unset a breakpoint there.
467Unsetting a breakpoint where none has been set has no effect.
468
469Reevaluating or reinstrumenting a definition forgets all its breakpoints.
470
471A @dfn{conditional breakpoint} tests a condition each time the program
472gets there. Any errors that occur as a result of evaluating the
473condition are ignored, as if the result were @code{nil}. To set a
474conditional breakpoint, use @kbd{x}, and specify the condition
475expression in the minibuffer. Setting a conditional breakpoint at a
476stop point that has a previously established conditional breakpoint puts
477the previous condition expression in the minibuffer so you can edit it.
478
479You can make a conditional or unconditional breakpoint
480@dfn{temporary} by using a prefix arg with the command to set the
481breakpoint. When a temporary breakpoint stops the program, it is
482automatically unset.
483
484Edebug always stops or pauses at a breakpoint except when the Edebug
485mode is Go-nonstop. In that mode, it ignores breakpoints entirely.
486
487To find out where your breakpoints are, use the @kbd{B} command, which
488moves point to the next breakpoint in the definition following point, or
489to the first breakpoint if there are no following breakpoints. This
490command does not continue execution---it just moves point in the buffer.
491
492@menu
493* Global Break Condition:: Breaking on an event.
494* Source Breakpoints:: Embedding breakpoints in source code.
495@end menu
496
497
498@node Global Break Condition
499@subsubsection Global Break Condition
500
501@cindex stopping on events
502@cindex global break condition
503 A @dfn{global break condition} stops execution when a specified
504condition is satisfied, no matter where that may occur. Edebug
505evaluates the global break condition at every stop point. If it
506evaluates to a non-@code{nil} value, then execution stops or pauses
507depending on the execution mode, as if a breakpoint had been hit. If
508evaluating the condition gets an error, execution does not stop.
509
510@findex edebug-set-global-break-condition
511@vindex edebug-global-break-condition
512 You can set or edit the condition expression, stored in
513@code{edebug-global-break-condition}, using the @kbd{X} command
514(@code{edebug-set-global-break-condition}).
515
516 The global break condition is the simplest way to find where in your
517code some event occurs, but it makes code run much more slowly. So you
518should reset the condition to @code{nil} when not using it.
519
520@node Source Breakpoints
521@subsubsection Source Breakpoints
522
523@findex edebug
524@cindex source breakpoints
525 All breakpoints in a definition are forgotten each time you
526reinstrument it. To make a breakpoint that won't be forgotten, you can
527write a @dfn{source breakpoint}, which is simply a call to the function
528@code{edebug} in your source code. You can, of course, make such a call
529conditional. For example, in the @code{fac} function, insert the first
530line as shown below to stop when the argument reaches zero:
531
532@example
533(defun fac (n)
534 (if (= n 0) (edebug))
535 (if (< 0 n)
536 (* n (fac (1- n)))
537 1))
538@end example
539
540When the @code{fac} definition is instrumented and the function is
541called, the call to @code{edebug} acts as a breakpoint. Depending on
542the execution mode, Edebug stops or pauses there.
543
544If no instrumented code is being executed when @code{edebug} is called,
545that function calls @code{debug}.
546@c This may not be a good idea anymore.
547
548@node Trapping Errors
549@subsection Trapping Errors
550
551Emacs normally displays an error message when an error is signaled and
552not handled with @code{condition-case}. While Edebug is active, it
553normally responds to all unhandled errors. You can customize this with
554the options @code{edebug-on-error} and @code{edebug-on-quit}; see
555@ref{Edebug Options}.
556
557When Edebug responds to an error, it shows the last stop point
558encountered before the error. This may be the location of a call to a
559function which was not instrumented, within which the error actually
560occurred. For an unbound variable error, the last known stop point
561might be quite distant from the offending variable reference. In that
562case you might want to display a full backtrace (@pxref{Edebug Misc}).
563
564If you change @code{debug-on-error} or @code{debug-on-quit} while
565Edebug is active, these changes will be forgotten when Edebug becomes
566inactive. Furthermore, during Edebug's recursive edit, these variables
567are bound to the values they had outside of Edebug.
568
569@ignore @c I don't want to document something that works only partly -- rms.
570Edebug can also trap signals even if they are handled. If
571@code{debug-on-error} is a list of signal names, Edebug will stop when
572any of these errors are signaled. Edebug shows you the last known stop
573point just as for unhandled errors. After you continue execution, the
574error is signaled again (but without being caught by Edebug). Edebug
575can only trap errors that are handled if they are signaled in Lisp code
576(not subroutines) since it does so by temporarily replacing the
577@code{signal} function.
578@end ignore
579
580@node Edebug Views
581@subsection Edebug Views
582
583These Edebug commands let you view aspects of the buffer and window
584status that obtained before entry to Edebug.
585
586@table @kbd
587@item v
588View the outside window configuration (@code{edebug-view-outside}).
589
590@item p
591Temporarily display the outside current buffer with point at its outside
592position (@code{edebug-bounce-point}). With a prefix argument @var{n},
593pause for @var{n} seconds instead.
594
595@item w
596Move point back to the current stop point (@code{edebug-where}) in the
597source code buffer. Also, if you use this command in a different window
598displaying the same buffer, that window will be used instead to display
599the current definition in the future.
600
601@item W
602Forget the saved outside window configuration---so that the current
603window configuration will remain unchanged when you next exit Edebug (by
604continuing the program). Also toggle the @code{edebug-save-windows}
605variable.
606@ignore @c This text is implementation-oriented and doesn't emphasize
607 what users really want to know.
608Toggle the @code{edebug-save-windows} variable which indicates whether
609the outside window configuration is saved and restored
610(@code{edebug-toggle-save-windows}). Also, each time it is toggled on,
611make the outside window configuration the same as the current window
612configuration.
613@end ignore
614@end table
615
616You can view the outside window configuration with @kbd{v} or just
617bounce to the point in the current buffer with @kbd{p}, even if
618it is not normally displayed. After moving point, you may wish to jump
619back to the stop point with @kbd{w} from a source code buffer.
620
621@ignore I don't understand this -- rms
622If you type @kbd{W} twice, Edebug continues saving and restoring an
623outside window configuration, but updates it to match the current
624configuration. You can use this to add another buffer to be displayed
625whenever Edebug is active. However, the automatic redisplay of
626@samp{*edebug*} and @samp{*edebug-trace*} may conflict with the buffers
627you wish to see unless you have enough windows open.
628
629With a prefix argument, @code{W} only toggles saving and restoring of
630the selected window. To specify a window that is not displaying the
631source code buffer, you must use @kbd{C-x X W} from the global keymap.
632@end ignore
633
634@node Edebug Eval
635@subsection Evaluation
636
637While within Edebug, you can evaluate expressions ``as if'' Edebug were
638not running. Edebug tries to be invisible to the expression's
639evaluation and printing. Evaluation of expressions that cause side
640effects will work as expected except for things that Edebug explicitly
641saves and restores. @xref{The Outside Context}, for details on this
642process.
643
644@table @kbd
645@item e @var{exp} @key{RET}
646Evaluate expression @var{exp} in the context outside of Edebug
647(@code{edebug-eval-expression}). That is, Edebug tries to minimize its
648interference with the evaluation.
649
650@item M-@key{ESC} @var{exp} @key{RET}
651Evaluate expression @var{exp} in the context of Edebug itself.
652
653@item C-x C-e
654Evaluate the expression before point, in the context outside of Edebug
655(@code{edebug-eval-last-sexp}).
656@end table
657
658@cindex lexical binding (Edebug)
659Edebug supports evaluation of expressions containing references to
660lexically bound symbols created by the following constructs in
661@file{cl.el} (version 2.03 or later): @code{lexical-let},
662@code{macrolet}, and @code{symbol-macrolet}.
663
664
665@node Eval List
666@subsection Evaluation List Buffer
667
668You can use the @dfn{evaluation list buffer}, called @samp{*edebug*}, to
669evaluate expressions interactively. You can also set up the
670@dfn{evaluation list} of expressions to be evaluated automatically each
671time Edebug updates the display.
672
673@table @kbd
674@item E
675Switch to the evaluation list buffer @samp{*edebug*}
676(@code{edebug-visit-eval-list}).
677@end table
678
679In the @samp{*edebug*} buffer you can use the commands of Lisp
680Interaction mode (@pxref{Lisp Interaction,,, emacs, The GNU Emacs
681Manual}) as well as these special commands:
682
683@table @kbd
684@item LFD
685Evaluate the expression before point, in the outside context, and insert
686the value in the buffer (@code{edebug-eval-print-last-sexp}).
687
688@item C-x C-e
689Evaluate the expression before point, in the context outside of Edebug
690(@code{edebug-eval-last-sexp}).
691
692@item C-c C-u
693Build a new evaluation list from contents of the buffer
694(@code{edebug-update-eval-list}).
695
696@item C-c C-d
697Delete the evaluation list group that point is in
698(@code{edebug-delete-eval-item}).
699
700@item C-c C-w
701Switch back to the source code buffer at the current stop point
702(@code{edebug-where}).
703@end table
704
705You can evaluate expressions in the evaluation list window with
706@kbd{LFD} or @kbd{C-x C-e}, just as you would in @samp{*scratch*};
707but they are evaluated in the context outside of Edebug.
708
709The expressions you enter interactively (and their results) are lost
710when you continue execution; but you can set up an @dfn{evaluation list}
711consisting of expressions to be evaluated each time execution stops.
712
713@cindex evaluation list group
714To do this, write one or more @dfn{evaluation list groups} in the
715evaluation list buffer. An evaluation list group consists of one or
716more Lisp expressions. Groups are separated by comment lines.
717
718The command @kbd{C-c C-u} (@code{edebug-update-eval-list}) rebuilds the
719evaluation list, scanning the buffer and using the first expression of
720each group.
721
722Be careful not to add expressions that execute instrumented code since
723that would cause an infinite loop.
724@c There ought to be a way to fix this.
725
726Redisplaying the evaluation list works by inserting each expression in
727the buffer, followed by its current value. It also inserts comment
728lines so that each expression becomes its own group. Thus, if you type
729@kbd{C-c C-u} again without changing the buffer text, the evaluation
730list is effectively unchanged.
731
732If an error occurs during an evaluation from the evaluation list, the
733error message is displayed in a string as if it were the result.
734Therefore, expressions that use variables not currently valid do not
735interrupt your debugging.
736
737Here is an example of what the evaluation list window looks like after
738several expressions have been added to it:
739
740@smallexample
741(current-buffer)
742#<buffer *scratch*>
743;---------------------------------------------------------------
744(selected-window)
745#<window 16 on *scratch*>
746;---------------------------------------------------------------
747(point)
748196
749;---------------------------------------------------------------
750bad-var
751"Symbol's value as variable is void: bad-var"
752;---------------------------------------------------------------
753(recursion-depth)
7540
755;---------------------------------------------------------------
756this-command
757eval-last-sexp
758;---------------------------------------------------------------
759@end smallexample
760
761To delete a group, move point into it and type @kbd{C-c C-d}, or simply
762delete the text for the group and update the evaluation list with
763@kbd{C-c C-u}. To add a new expression to the evaluation list, insert
764the expression at a suitable place, and insert a new comment line. (You
765need not insert dashes in the comment line---its contents don't matter.)
766Then type @kbd{C-c C-u}.
767
768After selecting @samp{*edebug*}, you can return to the source code
769buffer with @kbd{C-c C-w}. The @samp{*edebug*} buffer is killed when
770you continue execution, and recreated next time it is needed.
771
772
773@node Printing in Edebug
774@subsection Printing in Edebug
775
776@cindex printing (Edebug)
777@cindex printing circular structures
778@pindex cust-print
779 If an expression in your program produces a value containing circular
780list structure, you may get an error when Edebug attempts to print it.
781
782@vindex edebug-print-length
783@vindex edebug-print-level
784 One way to cope with circular structure is to set @code{print-length}
785or @code{print-level} to truncate the printing. Edebug does this for
786you; it binds @code{print-length} and @code{print-level} to 50 if they
787were @code{nil}. (Actually, the variables @code{edebug-print-length}
788and @code{edebug-print-level} specify the values to use within Edebug.)
789@xref{Output Variables}.
790
791 You can also print circular structures and structures that share
792elements more informatively by using the @file{cust-print} package.
793
794 To load @file{cust-print} and activate custom printing only for
795Edebug, simply use the command @kbd{M-x edebug-install-custom-print}.
796To restore the standard print functions, use @kbd{M-x
797edebug-uninstall-custom-print}.
798
799 Here is an example of code that creates a circular structure:
800
801@example
802(setq a '(x y))
803(setcar a a))
804@end example
805
806@noindent
807Custom printing prints this as @samp{Result: #1=(#1# y)}. The
808@samp{#1=} notation labels the structure that follows it with the label
809@samp{1}, and the @samp{#1#} notation references the previously labelled
810structure. This notation is used for any shared elements of lists or
811vectors.
812
813 Other programs can also use custom printing; see @file{cust-print.el}
814for details.
815
816@node Trace Buffer
817@subsection Trace Buffer
818@cindex trace buffer
819
820 Edebug can record an execution trace in a buffer named
821@samp{*edebug-trace*}. This is a log of function calls and returns,
822showing the function names and their arguments and values. To enable
823trace recording, set @code{edebug-trace} to a non-@code{nil} value.
824
825 Making a trace buffer is not the same thing as using trace execution
826mode (@pxref{Edebug Execution Modes}).
827
828 When trace recording is enabled, each function entry and exit adds
829lines to the trace buffer. A function entry record looks like
830@samp{::::@{} followed by the function name and argument values. A
831function exit record looks like @samp{::::@}} followed by the function
832name and result of the function.
833
834 The number of @samp{:}s in an entry shows its recursion depth. You
835can use the braces in the trace buffer to find the matching beginning or
836end of function calls.
837
838@findex edebug-print-trace-before
839@findex edebug-print-trace-after
840 You can customize trace recording for function entry and exit by
841redefining the functions @code{edebug-print-trace-before} and
842@code{edebug-print-trace-after}.
843
844@defmac edebug-tracing string body@dots{}
845This macro requests additional trace information around the execution
846of the @var{body} forms. The argument @var{string} specifies text
847to put in the trace buffer. All the arguments are evaluated.
848@code{edebug-tracing} returns the value of the last form in @var{body}.
849@end defmac
850
851@defun edebug-trace format-string &rest format-args
852This function inserts text in the trace buffer. It computes the text
853with @code{(apply 'format @var{format-string} @var{format-args})}.
854It also inserts a newline to separate entries.
855@end defun
856
857 @code{edebug-tracing} and @code{edebug-trace} insert lines in the trace
858buffer even if Edebug is not active.
859
860 Adding text to the trace buffer also scrolls its window to show the
861last lines inserted.
862
863@ignore @c too vague
864There may be some display problems if you use
865tracing along with the evaluation list.
866@end ignore
867
868@node Coverage Testing
869@subsection Coverage Testing
870
871@cindex coverage testing
872@cindex frequency counts
873@cindex performance analysis
874Edebug provides rudimentary coverage testing and display of execution
875frequency. All execution of an instrumented function accumulates
876frequency counts, both before and after evaluation of each instrumented
877expression, even if the execution mode is Go-nonstop. Coverage testing
878is more expensive, so it is only done if @code{edebug-test-coverage} is
879non-@code{nil}. The command @kbd{M-x edebug-display-freq-count}
880displays both the frequency data and the coverage data (if recorded).
881
882@deffn Command edebug-display-freq-count
883This command displays the frequency count data for each line of the
884current definition.
885
886The frequency counts appear comment lines after each line of code, and
887you can undo all insertions with one @code{undo} command. The counts
888are appear under the @kbd{(} before an expression or the @kbd{)} after
889an expression, or on the last character of a symbol. Values do not appear if
890they are equal to the previous count on the same line.
891
892The character @samp{=} following the count for an expression says that
893the expression has returned the same value each time it was evaluated
894This is the only coverage information that Edebug records.
895
896To clear the frequency count and coverage data for a definition,
897reinstrument it.
898@end deffn
899
900For example, after evaluating @code{(fac 5)} with a source
901breakpoint, and setting @code{edebug-test-coverage} to @code{t}, when
902the breakpoint is reached, the frequency data looks like this:
903
904@example
905(defun fac (n)
906 (if (= n 0) (edebug))
907;#6 1 0 =5
908 (if (< 0 n)
909;#5 =
910 (* n (fac (1- n)))
911;# 5 0
912 1))
913;# 0
914@end example
915
916The comment lines show that @code{fac} has been called 6 times. The
917first @code{if} statement has returned 5 times with the same result each
918time; the same is true of the condition on the second @code{if}.
919The recursive call of @code{fac} has not returned at all.
920
921
922@node The Outside Context
923@subsection The Outside Context
924
925Edebug tries to be transparent to the program you are debugging, but it
926does not succeed completely. Edebug also tries to be transparent when
927you evaluate expressions with @kbd{e} or with the evaluation list
928buffer, by temporarily restoring the outside context. This section
929explains precisely what context Edebug restores, and how Edebug fails to
930be completely transparent.
931
932@c This can be fixed and should be
933The same mechanism that avoids masking certain variable's outside values
934also currently makes it impossible to set these variables within Edebug.
935
936@menu
937* Checking Whether to Stop:: When Edebug decides what to do.
938* Edebug Display Update:: When Edebug updates the display.
939* Edebug Recursive Edit:: When Edebug stops execution.
940@end menu
941
942@node Checking Whether to Stop
943@subsubsection Checking Whether to Stop
944
945Whenever Edebug is entered just to think about whether to take some
946action, it needs to save and restore certain data.
947
948@itemize @bullet
949@item
950@code{max-lisp-eval-depth} and @code{max-specpdl-size} are both
951incremented one time to reduce Edebug's impact on the stack.
952You could, however, still run out of stack space when using Edebug.
953
954@item
955The state of keyboard macro execution is saved and restored. While
956Edebug is active, @code{executing-macro} is bound to
957@code{edebug-continue-kbd-macro}.
958
959@end itemize
960
961
962@node Edebug Display Update
963@subsubsection Edebug Display Update
964
965When Edebug needs to display something (e.g., in trace mode), it saves
966the current window configuration from ``outside'' Edebug (@pxref{Window
967Configurations,,, elisp, GNU Emacs Lisp Reference Manual}). When
968you exit Edebug (by continuing the program), it restores the previous
969window configuration.
970
971Emacs redisplays only when it pauses. Usually, when you continue
972execution, the program comes back into Edebug at a breakpoint or after
973stepping without pausing or reading input in between. In such cases,
974Emacs never gets a chance to redisplay the ``outside'' configuration.
975What you see is the same window configuration as the last time Edebug
976was active, with no interruption.
977
978Entry to Edebug for displaying something also saves and restores the
979following data, but some of these are deliberately not restored if an
980error or quit signal occurs.
981
982@itemize @bullet
983@item
984@cindex current buffer point and mark (Edebug)
985Which buffer is current, and the positions of point and the mark in the
986current buffer, are saved and restored.
987
988@item
989@cindex window configuration (Edebug)
990The outside window configuration is saved and restored if
991@code{edebug-save-windows} is non-@code{nil} (@pxref{Edebug Display Update}).
992
993The window configuration is not restored on error or quit, but the
994outside selected window @emph{is} reselected even on error or quit in
995case a @code{save-excursion} is active. If the value of
996@code{edebug-save-windows} is a list, only the listed windows are saved
997and restored.
998
999The window start and horizontal scrolling of the source code buffer are
1000not restored, however, so that the display remains coherent within Edebug.
1001
1002@item
1003@vindex edebug-save-displayed-buffer-points
1004The value of point in each displayed buffer is saved and restored if
1005@code{edebug-save-displayed-buffer-points} is non-@code{nil}.
1006
1007@item
1008The variables @code{overlay-arrow-position} and
1009@code{overlay-arrow-string} are saved and restored. So you can safely
1010invoke Edebug from the recursive edit elsewhere in the same buffer.
1011
1012@item
1013@code{cursor-in-echo-area} is locally bound to @code{nil} so that
1014the cursor shows up in the window.
1015@end itemize
1016
1017@node Edebug Recursive Edit
1018@subsubsection Edebug Recursive Edit
1019
1020When Edebug is entered and actually reads commands from the user, it
1021saves (and later restores) these additional data:
1022
1023@itemize @bullet
1024@item
1025The current match data. @xref{Match Data}.
1026
1027@item
1028@code{last-command}, @code{this-command}, @code{last-command-char},
1029@code{last-input-char}, @code{last-input-event},
1030@code{last-command-event}, @code{last-event-frame},
1031@code{last-nonmenu-event}, and @code{track-mouse}. Commands used within
1032Edebug do not affect these variables outside of Edebug.
1033
1034The key sequence returned by @code{this-command-keys} is changed by
1035executing commands within Edebug and there is no way to reset
1036the key sequence from Lisp.
1037
1038@item
1039Complex commands executed while in Edebug are added to the variable
1040@code{command-history}. In rare cases this can alter execution.
1041
1042@item
1043Within Edebug, the recursion depth appears one deeper than the recursion
1044depth outside Edebug. This is not true of the automatically updated
1045evaluation list window.
1046
1047@item
1048@code{standard-output} and @code{standard-input} are bound to @code{nil}
1049by the @code{recursive-edit}, but Edebug temporarily restores them during
1050evaluations.
1051
1052@item
1053The state of keyboard macro definition is saved and restored. While
1054Edebug is active, @code{defining-kbd-macro} is bound to
1055@code{edebug-continue-kbd-macro}.
1056@end itemize
1057
1058@node Instrumenting Macro Calls
1059@subsection Instrumenting Macro Calls
1060
1061When Edebug instruments an expression that calls a Lisp macro, it needs
1062additional advice to do the job properly. This is because there is no
1063way to tell which subexpressions of the macro call are forms to be
1064evaluated. (Evaluation may occur explicitly in the macro body, or when
1065the resulting expansion is evaluated, or any time later.) You must
1066explain the format of calls to each macro to enable Edebug to handle it.
1067To do this, use @code{def-edebug-form-spec} to define the format of
1068calls to a given macro.
1069
1070@deffn Macro def-edebug-spec macro specification
1071Specify which expressions of a call to macro @var{macro} are forms to be
1072evaluated. For simple macros, the @var{specification} often looks very
1073similar to the formal argument list of the macro definition, but
1074specifications are much more general than macro arguments.
1075
1076The @var{macro} argument may actually be any symbol, not just a macro
1077name.
1078@end deffn
1079
1080Here is a simple example that defines the specification for the
1081@code{for} macro described in the Emacs Lisp Reference Manual, followed
1082by an alternative, equivalent specification.
1083
1084@example
1085(def-edebug-spec for
1086 (symbolp "from" form "to" form "do" &rest form))
1087
1088(def-edebug-spec for
1089 (symbolp ['from form] ['to form] ['do body]))
1090@end example
1091
1092Here is a table of the possibilities for @var{specification} and how each
1093directs processing of arguments.
1094
1095@table @bullet
1096
1097@item @code{t}
1098All arguments are instrumented for evaluation.
1099
1100@item @code{0}
1101None of the arguments is instrumented.
1102
1103@item a symbol
1104The symbol must have an Edebug specification which is used instead.
1105This indirection is repeated until another kind of specification is
1106found. This allows you to inherit the specification for another macro.
1107
1108@item a list
1109The elements of the list describe the types of the arguments of a
1110calling form. The possible elements of a specification list are
1111described in the following sections.
1112@end table
1113
1114@menu
1115* Specification List:: How to specify complex patterns of evaluation.
1116* Backtracking:: What Edebug does when matching fails.
1117@c * Debugging Backquote:: Debugging Backquote
1118* Specification Examples:: To help understand specifications.
1119@end menu
1120
1121
1122@node Specification List
1123@subsubsection Specification List
1124
1125@cindex Edebug specification list
1126A @dfn{specification list} is required for an Edebug specification if
1127some arguments of a macro call are evaluated while others are not. Some
1128elements in a specification list match one or more arguments, but others
1129modify the processing of all following elements. The latter, called
1130@dfn{specification keywords}, are symbols beginning with @samp{&} (such
1131as @code{&optional}).
1132
1133A specification list may contain sublists which match arguments that are
1134themselves lists, or it may contain vectors used for grouping. Sublists
1135and groups thus subdivide the specification list into a hierarchy of
1136levels. Specification keywords only apply to the remainder of the
1137sublist or group they are contained in.
1138
1139When a specification list involves alternatives or repetition, matching
1140it against an actual macro call may require backtracking.
1141@xref{Backtracking}, for more details.
1142
1143Edebug specifications provide the power of regular expression matching,
1144plus some context-free grammar constructs: the matching of sublists with
1145balanced parentheses, recursive processing of forms, and recursion via
1146indirect specifications.
1147
1148Here's a table of the possible elements of a specification list, with
1149their meanings:
1150
1151@table @code
1152@item sexp
1153A single unevaluated Lisp object object.
1154
1155@item form
1156A single evaluated expression, which is instrumented.
1157
1158@item place
1159@findex edebug-unwrap
1160A place to store a value, as in the Common Lisp @code{setf} construct.
1161
1162@item body
1163Short for @code{&rest form}. See @code{&rest} below.
1164
1165@item function-form
1166A function form: either a quoted function symbol, a quoted lambda
1167expression, or a form (that should evaluate to a function symbol or
1168lambda expression). This is useful when an argument that's a lambda
1169expression might be quoted with @code{quote} rather than
1170@code{function}, since it instruments the body of the lambda expression
1171either way.
1172
1173@item lambda-expr
1174A lambda expression with no quoting.
1175
1176@item &optional
1177@kindex &optional @r{(Edebug)}
1178All following elements in the specification list are optional; as soon
1179as one does not match, Edebug stops matching at this level.
1180
1181To make just a few elements optional followed by non-optional elements,
1182use @code{[&optional @var{specs}@dots{}]}. To specify that several
1183elements must all match or none, use @code{&optional
1184[@var{specs}@dots{}]}. See the @code{defun} example below.
1185
1186@item &rest
1187@kindex &rest @r{(Edebug)}
1188All following elements in the specification list are repeated zero or
1189more times. All the elements need not match in the last repetition,
1190however.
1191
1192To repeat only a few elements, use @code{[&rest @var{specs}@dots{}]}.
1193To specify several elements that must all match on every repetition, use
1194@code{&rest [@var{specs}@dots{}]}.
1195
1196@item &or
1197@kindex &or @r{(Edebug)}
1198Each of the following elements in the specification list is an
1199alternative. One of the alternatives must match, or the @code{&or}
1200specification fails.
1201
1202Each list element following @code{&or} is a single alternative. To
1203group two or more list elements as a single alternative, enclose them in
1204@code{[@dots{}]}.
1205
1206@item &not
1207@kindex &not @r{(Edebug)}
1208Each of the following elements is matched as alternatives as if by using
1209@code{&or}, but if any of them match, the specification fails. If none
1210of them match, nothing is matched, but the @code{&not} specification
1211succeeds.
1212
1213@item &define
1214@kindex &define @r{(Edebug)}
1215Indicates that the specification is for a defining form. The defining
1216form itself is not instrumented (i.e. Edebug does not stop before and
1217after the defining form), but forms inside it typically will be
1218instrumented. The @code{&define} keyword should be the first element in
1219a list specification.
1220
1221@item nil
1222This is successful when there are no more arguments to match at the
1223current argument list level; otherwise it fails. See sublist
1224specifications and the backquote example below.
1225
1226@item gate
1227@cindex preventing backtracking
1228No argument is matched but backtracking through the gate is disabled
1229while matching the remainder of the specifications at this level. This
1230is primarily used to generate more specific syntax error messages. See
1231@ref{Backtracking}, for more details. Also see the @code{let} example
1232below.
1233
1234@item @var{other-symbol}
1235@cindex indirect specifications
1236Any other symbol in a specification list may be a predicate or an
1237indirect specification.
1238
1239If the symbol has an Edebug specification, this @dfn{indirect
1240specification} should be either a list specification that is used in
1241place of the symbol, or a function that is called to process the
1242arguments. The specification may be defined with @code{def-edebug-spec}
1243just as for macros. See the @code{defun} example below.
1244
1245Otherwise, the symbol should be a predicate. The predicate is called
1246with the argument and the specification fails if the predicate returns
1247@code{nil}. In either case, that argument is not instrumented.
1248
1249@findex keywordp
1250@findex lambda-list-keywordp
1251Some suitable predicates include @code{symbolp}, @code{integerp},
1252@code{stringp}, @code{vectorp}, and @code{atom}.
1253@ignore
1254, @code{keywordp}, and
1255@code{lambda-list-keywordp}. The last two, defined in @file{edebug.el},
1256test whether the argument is a symbol starting with @samp{@code{:}} and
1257@samp{@code{&}} respectively.
1258@end ignore
1259
1260@item [@var{elements}@dots{}]
1261@cindex [@dots{}] (Edebug)
1262A vector of elements groups the elements into a single @dfn{group
1263specification}. Its meaning has nothing to do with vectors.
1264
1265@item "@var{string}"
1266The argument should be a symbol named @var{string}. This specification
1267is equivalent to the quoted symbol, @code{'@var{symbol}}, where the name
1268of @var{symbol} is the @var{string}, but the string form is preferred.
1269
1270@ignore
1271@item '@var{symbol} @r{or} (quote @var{symbol})
1272The argument should be the symbol @var{symbol}. But use a string
1273specification instead.
1274@end ignore
1275
1276@item (vector @var{elements}@dots{})
1277The argument should be a vector whose elements must match the
1278@var{elements} in the specification. See the backquote example below.
1279
1280@item (@var{elements}@dots{})
1281Any other list is a @dfn{sublist specification} and the argument must be
1282a list whose elements match the specification @var{elements}.
1283
1284@cindex dotted lists (Edebug)
1285A sublist specification may be a dotted list and the corresponding list
1286argument may then be a dotted list. Alternatively, the last @sc{cdr} of a
1287dotted list specification may be another sublist specification (via a
1288grouping or an indirect specification, e.g. @code{(spec . [(more
1289specs@dots{})])}) whose elements match the non-dotted list arguments.
1290This is useful in recursive specifications such as in the backquote
1291example below. Also see the description of a @code{nil} specification
1292above for terminating such recursion.
1293
1294Note that a sublist specification of the form @code{(specs . nil)}
1295means the same as @code{(specs)}, and @code{(specs .
1296(sublist-elements@dots{}))} means the same as @code{(specs
1297sublist-elements@dots{})}.
1298@end table
1299
1300@c Need to document extensions with &symbol and :symbol
1301
1302Here is a list of additional specifications that may only appear after
1303@code{&define}. See the @code{defun} example below.
1304
1305@table @code
1306@item name
1307The argument, a symbol, is the name of the defining form.
1308
1309A defining form is not required to have a name field; and it may have
1310multiple name fields.
1311
1312@item :name
1313This construct does not actually match an argument. The element
1314following @code{:name} should be a symbol; it is used as an additional
1315name component for the definition. You can use this to add a unique,
1316static component to the name of the definition. It may be used more
1317than once.
1318
1319@item arg
1320The argument, a symbol, is the name of an argument of the defining form.
1321However, lambda list keywords (symbols starting with @samp{@code{&}})
1322are not allowed. See @code{lambda-list} and the example below.
1323
1324@item lambda-list
1325@cindex lambda-list (Edebug)
1326This matches a lambda list---the argument list of a lambda expression.
1327The argument should be a list of symbols.
1328
1329@item def-body
1330The argument is the body of code in a definition. This is like
1331@code{body}, described above, but a definition body must be instrumented
1332with a different Edebug call that looks up information associated with
1333the definition. Use @code{def-body} for the highest level list of forms
1334within the definition.
1335
1336@item def-form
1337The argument is a single, highest-level form in a definition. This is
1338like @code{def-body}, except use this to match a single form rather than
1339a list of forms. As a special case, @code{def-form} also means that
1340tracing information is not output when the form is executed. See the
1341@code{interactive} example below.
1342@end table
1343
1344@node Backtracking
1345@subsubsection Backtracking
1346
1347@cindex backtracking
1348@cindex syntax error (Edebug)
1349If a specification fails to match at some point, this does not
1350necessarily mean a syntax error will be signaled; instead,
1351@dfn{backtracking} will take place until all alternatives have been
1352exhausted. Eventually every element of the argument list must be
1353matched by some element in the specification, and every required element
1354in the specification must match some argument.
1355
1356Backtracking is disabled for the remainder of a sublist or group when
1357certain conditions occur, described below. Backtracking is reenabled
1358when a new alternative is established by @code{&optional}, @code{&rest},
1359or @code{&or}. It is also reenabled initially when processing a
1360sublist or group specification or an indirect specification.
1361
1362You might want to disable backtracking to commit to some alternative so
1363that Edebug can provide a more specific syntax error message. Normally,
1364if no alternative matches, Edebug reports that none matched, but if one
1365alternative is committed to, Edebug can report how it failed to match.
1366
1367First, backtracking is disabled while matching any of the form
1368specifications (i.e. @code{form}, @code{body}, @code{def-form}, and
1369@code{def-body}). These specifications will match any form so any error
1370must be in the form itself rather than at a higher level.
1371
1372Second, backtracking is disabled after successfully matching a quoted
1373symbol or string specification, since this usually indicates a
1374recognized construct. If you have a set of alternative constructs that
1375all begin with the same symbol, you can usually work around this
1376constraint by factoring the symbol out of the alternatives, e.g.,
1377@code{["foo" &or [first case] [second case] ...]}.
1378
1379Third, backtracking may be explicitly disabled by using the
1380@code{gate} specification. This is useful when you know that
1381no higher alternatives may apply.
1382
1383@ignore
1384@node Debugging Backquote
1385@subsubsection Debugging Backquote
1386
1387@findex ` (Edebug)
1388@cindex backquote (Edebug)
1389Backquote (@kbd{`}) is a macro that results in an expression that may or
1390may not be evaluated. It is often used to simplify the definition of a
1391macro to return an expression to be evaluated, but Edebug cannot know
1392whether the resyult of backquote will be used in any other way.
1393
1394The forms inside unquotes (@code{,} and @code{,@@}) are evaluated, and
1395Edebug instruments them.
1396
1397Edebug supports nested backquotes, but there is a limit on the support
1398of quotes inside of backquotes. Forms quoted with @code{'} are not
1399normally evaluated, but if the quoted form appears immediately within
1400@code{,} and @code{,@@} forms, Edebug treats this as a backquoted form
1401at the next higher level (even if there is not a next higher level; this
1402is difficult to fix).
1403
1404@findex edebug-`
1405If the backquoted forms are code to be evaluated, you can have Edebug
1406instrument them by using @code{edebug-`} instead of the regular
1407@code{`}. Unquoting forms can be used inside @code{edebug-`} anywhere a
1408form is normally allowed. But @code{(, @var{form})} may be used in two
1409other places specially recognized by Edebug: wherever a predicate
1410specification would match, and at the head of a list form where the
1411function name normally appears. The @var{form} inside a spliced
1412unquote, @code{(,@@ @var{form})}, will be instrumented, but the unquote
1413form itself will not be instrumented since this would interfere with the
1414splicing.
1415
1416There is one other complication with using @code{edebug-`}. If the
1417@code{edebug-`} call is in a macro and the macro may be called from code
1418that is also instrumented, and if unquoted forms contain any macro
1419arguments bound to instrumented forms, then you should modify the
1420specification for the macro as follows: the specifications for those
1421arguments must use @code{def-form} instead of @code{form}. (This is to
1422reestablish the Edebugging context for those external forms.)
1423
1424For example, the @code{for} macro (@pxref{Problems with Macros,,, elisp,
1425Emacs Lisp Reference Manual}) is shown here but with @code{edebug-`}
1426substituted for regular @code{`}.
1427
1428@example
1429(defmacro inc (var)
1430 (list 'setq var (list '1+ var)))
1431
1432(defmacro for (var from init to final do &rest body)
1433 (let ((tempvar (make-symbol "max")))
1434 (edebug-` (let (((, var) (, init))
1435 ((, tempvar) (, final)))
1436 (while (<= (, var) (, tempvar))
1437 (,@ body)
1438 (inc (, var)))))))
1439@end example
1440
1441Here is the corresponding modified Edebug specification and a
1442call of the macro:
1443
1444@example
1445(def-edebug-spec for
1446 (symbolp "from" def-form "to" def-form "do" &rest def-form))
1447
1448(let ((n 5))
1449 (for i from n to (* n (+ n 1)) do
1450 (message "%s" i)))
1451@end example
1452
1453After instrumenting the @code{for} macro and the macro call, Edebug
1454first steps to the beginning of the macro call, then into the macro
1455body, then through each of the unquoted expressions in the backquote
1456showing the expressions that will be embedded. Then when the macro
1457expansion is evaluated, Edebug will step through the @code{let} form and
1458each time it gets to an unquoted form, it will jump back to an argument
1459of the macro call to step through that expression. Finally stepping
1460will continue after the macro call. Even more convoluted execution
1461paths may result when using anonymous functions.
1462
1463@vindex edebug-unwrap-results
1464When the result of an expression is an instrumented expression, it is
1465difficult to see the expression inside the instrumentation. So
1466you may want to set the option @code{edebug-unwrap-results} to a
1467non-@code{nil} value while debugging such expressions, but it would slow
1468Edebug down to always do this.
1469
1470@end ignore
1471@node Specification Examples
1472@subsubsection Specification Examples
1473
1474It may be easier to understand Edebug specifications by studying
1475the examples provided here.
1476
1477A @code{let} special form has a sequence of bindings and a body. Each
1478of the bindings is either a symbol or a sublist with a symbol and
1479optional value. In the specification below, notice the @code{gate}
1480inside of the sublist to prevent backtracking once a sublist is found.
1481
1482@example
1483(def-edebug-spec let
1484 ((&rest
1485 &or symbolp (gate symbolp &optional form))
1486 body))
1487@end example
1488
1489Edebug uses the following specifications for @code{defun} and
1490@code{defmacro} and the associated argument list and @code{interactive}
1491specifications. It is necessary to handle interactive forms specially
1492since an expression argument it is actually evaluated outside of the
1493function body.
1494
1495@example
1496(def-edebug-spec defmacro defun) ; @r{Indirect ref to @code{defun} spec}
1497(def-edebug-spec defun
1498 (&define name lambda-list
1499 [&optional stringp] ; @r{Match the doc string, if present.}
1500 [&optional ("interactive" interactive)]
1501 def-body))
1502
1503(def-edebug-spec lambda-list
1504 (([&rest arg]
1505 [&optional ["&optional" arg &rest arg]]
1506 &optional ["&rest" arg]
1507 )))
1508
1509(def-edebug-spec interactive
1510 (&optional &or stringp def-form)) ; @r{Notice: @code{def-form}}
1511@end example
1512
1513The specification for backquote below illustrates how to match
1514dotted lists and use @code{nil} to terminate recursion. It also
1515illustrates how components of a vector may be matched. (The actual
1516specification defined by Edebug does not support dotted lists because
1517doing so causes very deep recursion that could fail.)
1518
1519@example
1520(def-edebug-spec ` (backquote-form)) ;; alias just for clarity
1521
1522(def-edebug-spec backquote-form
1523 (&or ([&or "," ",@@"] &or ("quote" backquote-form) form)
1524 (backquote-form . [&or nil backquote-form])
1525 (vector &rest backquote-form)
1526 sexp))
1527@end example
1528
1529
1530@node Edebug Options
1531@subsection Edebug Options
1532
1533 These options affect the behavior of Edebug:
1534
1535@defopt edebug-setup-hook
1536Functions to call before Edebug is used. Each time it is set to a new
1537value, Edebug will call those functions once and then
1538@code{edebug-setup-hook} is reset to @code{nil}. You could use this to
1539load up Edebug specifications associated with a package you are using
1540but only when you also use Edebug.
1541@xref{Instrumenting}.
1542@end defopt
1543
1544@defopt edebug-all-defs
1545If this is non-@code{nil}, normal evaluation of defining forms such as
1546@code{defun} and @code{defmacro} instruments them for Edebug. This
1547applies to @code{eval-defun}, @code{eval-region}, and
1548@code{eval-current-buffer}. @xref{Instrumenting}.
1549@end defopt
1550
1551@defopt edebug-all-forms
1552If this is non-@code{nil}, the commands @code{eval-defun}, @code{eval-region},
1553and @code{eval-current-buffer} instrument all forms, even those that
1554don't define anything.
1555
1556Use the command @kbd{M-x edebug-all-forms} to toggle the value of this
1557option.
1558@xref{Instrumenting}.
1559@end defopt
1560
1561@defopt edebug-save-windows
1562If this is non-@code{nil}, Edebug saves and restores the window
1563configuration. That takes some time, so if your program does not care
1564what happens to the window configurations, it is better to set this
1565variable to @code{nil}.
1566
1567If the value is a list, only the listed windows are saved and
1568restored.
1569
1570You can use the @kbd{W} command in Edebug to change this variable
1571interactively. @xref{Edebug Display Update}.
1572@end defopt
1573
1574@defopt edebug-save-displayed-buffer-points
1575If non-@code{nil}, Edebug saves and restores point in all buffers.
1576
1577Saving and restoring point in other buffers is necessary if you are
1578debugging code that changes the point of a buffer which is displayed in
1579a non-selected window. If Edebug or the user then selects the window,
1580the buffer's point will change to the window's point.
1581
1582Saving and restoring point in all buffers is expensive, since it
1583requires selecting each window twice, so enable this only if you need
1584it. @xref{Edebug Display Update}.
1585@end defopt
1586
1587@defopt edebug-initial-mode
1588If this variable is non-@code{nil}, it specifies the initial execution
1589mode for Edebug when it is first activated. Possible values are
1590@code{step}, @code{next}, @code{go}, @code{Go-nonstop}, @code{trace},
1591@code{Trace-fast}, @code{continue}, and @code{Continue-fast}.
1592
1593The default value is @code{step}.
1594@xref{Edebug Execution Modes}.
1595@end defopt
1596
1597@defopt edebug-trace
1598@findex edebug-print-trace-before
1599@findex edebug-print-trace-after
1600Non-@code{nil} means display a trace of function entry and exit.
1601Tracing output is displayed in a buffer named @samp{*edebug-trace*}, one
1602function entry or exit per line, indented by the recursion level.
1603
1604The default value is @code{nil}.
1605
1606Also see @code{edebug-tracing}.
1607@xref{Tracing}.
1608@end defopt
1609
1610@defopt edebug-test-coverage
1611If non-@code{nil}, Edebug tests coverage of all expressions debugged.
1612This is done by comparing the result of each expression
1613with the previous result. Coverage is considered OK if two different
1614results are found. So to sufficiently test the coverage of your code,
1615try to execute it under conditions that evaluate all expressions more
1616than once, and produce different results for each expression.
1617
1618Use @kbd{M-x edebug-display-freq-count} to display the frequency count
1619and coverage information for a definition.
1620@xref{Coverage Testing}.
1621@end defopt
1622
1623@defopt edebug-continue-kbd-macro
1624If non-@code{nil}, continue defining or executing any keyboard macro
1625that is executing outside of Edebug. Use this with caution since it is not
1626debugged.
1627@xref{Edebug Execution Modes}.
1628@end defopt
1629
1630@defopt edebug-print-length
1631If non-@code{nil}, bind @code{print-length} to this while printing
1632results in Edebug. The default value is @code{50}.
1633@xref{Printing in Edebug}.
1634@end defopt
1635
1636@defopt edebug-print-level
1637If non-@code{nil}, bind @code{print-level} to this while printing
1638results in Edebug. The default value is @code{50}.
1639@end defopt
1640
1641@defopt edebug-print-circle
1642If non-@code{nil}, bind @code{print-circle} to this while printing
1643results in Edebug. The default value is @code{nil}.
1644@end defopt
1645
1646@defopt edebug-on-error
1647Edebug binds @code{debug-on-error} to this value, if
1648@code{debug-on-error} was previously @code{nil}. @xref{Trapping
1649Errors}.
1650@end defopt
1651
1652@defopt edebug-on-quit
1653Edebug binds @code{debug-on-quit} to this value, if
1654@code{debug-on-quit} was previously @code{nil}. @xref{Trapping
1655Errors}.
1656@end defopt
1657
1658 If you change the values of @code{edebug-on-error} or
1659@code{edebug-on-quit} while Edebug is active, their values won't be used
1660until the @emph{next} time Edebug is invoked at a deeper command level.
1661
1662@ignore
1663@defopt edebug-unwrap-results
1664Non-@code{nil} if Edebug should unwrap results of expressions. This is
1665useful when debugging macros where the results of expressions are
1666instrumented expressions. But don't do this when results might be
1667circular, or an infinite loop will result. @xref{Debugging Backquote}.
1668@end defopt
1669@end ignore
1670
1671@defopt edebug-global-break-condition
1672If non-@code{nil}, an expression to test for at every stop point.
1673If the result is non-nil, then break. Errors are ignored.
1674@xref{Global Break Condition}.
1675@end defopt
1676
diff --git a/lispref/eval.texi b/lispref/eval.texi
new file mode 100644
index 00000000000..c9b851f6b54
--- /dev/null
+++ b/lispref/eval.texi
@@ -0,0 +1,695 @@
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/eval
6@node Evaluation, Control Structures, Symbols, Top
7@chapter Evaluation
8@cindex evaluation
9@cindex interpreter
10@cindex interpreter
11@cindex value of expression
12
13 The @dfn{evaluation} of expressions in Emacs Lisp is performed by the
14@dfn{Lisp interpreter}---a program that receives a Lisp object as input
15and computes its @dfn{value as an expression}. How it does this depends
16on the data type of the object, according to rules described in this
17chapter. The interpreter runs automatically to evaluate portions of
18your program, but can also be called explicitly via the Lisp primitive
19function @code{eval}.
20
21@ifinfo
22@menu
23* Intro Eval:: Evaluation in the scheme of things.
24* Eval:: How to invoke the Lisp interpreter explicitly.
25* Forms:: How various sorts of objects are evaluated.
26* Quoting:: Avoiding evaluation (to put constants in the program).
27@end menu
28
29@node Intro Eval
30@section Introduction to Evaluation
31
32 The Lisp interpreter, or evaluator, is the program which computes
33the value of an expression which is given to it. When a function
34written in Lisp is called, the evaluator computes the value of the
35function by evaluating the expressions in the function body. Thus,
36running any Lisp program really means running the Lisp interpreter.
37
38 How the evaluator handles an object depends primarily on the data
39type of the object.
40@end ifinfo
41
42@cindex forms
43@cindex expression
44 A Lisp object which is intended for evaluation is called an
45@dfn{expression} or a @dfn{form}. The fact that expressions are data
46objects and not merely text is one of the fundamental differences
47between Lisp-like languages and typical programming languages. Any
48object can be evaluated, but in practice only numbers, symbols, lists
49and strings are evaluated very often.
50
51 It is very common to read a Lisp expression and then evaluate the
52expression, but reading and evaluation are separate activities, and
53either can be performed alone. Reading per se does not evaluate
54anything; it converts the printed representation of a Lisp object to the
55object itself. It is up to the caller of @code{read} whether this
56object is a form to be evaluated, or serves some entirely different
57purpose. @xref{Input Functions}.
58
59 Do not confuse evaluation with command key interpretation. The
60editor command loop translates keyboard input into a command (an
61interactively callable function) using the active keymaps, and then
62uses @code{call-interactively} to invoke the command. The execution of
63the command itself involves evaluation if the command is written in
64Lisp, but that is not a part of command key interpretation itself.
65@xref{Command Loop}.
66
67@cindex recursive evaluation
68 Evaluation is a recursive process. That is, evaluation of a form may
69call @code{eval} to evaluate parts of the form. For example, evaluation
70of a function call first evaluates each argument of the function call,
71and then evaluates each form in the function body. Consider evaluation
72of the form @code{(car x)}: the subform @code{x} must first be evaluated
73recursively, so that its value can be passed as an argument to the
74function @code{car}.
75
76@cindex environment
77 The evaluation of forms takes place in a context called the
78@dfn{environment}, which consists of the current values and bindings of
79all Lisp variables.@footnote{This definition of ``environment'' is
80specifically not intended to include all the data which can affect the
81result of a program.} Whenever the form refers to a variable without
82creating a new binding for it, the value of the binding in the current
83environment is used. @xref{Variables}.
84
85@cindex side effect
86 Evaluation of a form may create new environments for recursive
87evaluation by binding variables (@pxref{Local Variables}). These
88environments are temporary and vanish by the time evaluation of the form
89is complete. The form may also make changes that persist; these changes
90are called @dfn{side effects}. An example of a form that produces side
91effects is @code{(setq foo 1)}.
92
93 Finally, evaluation of one particular function call, @code{byte-code},
94invokes the @dfn{byte-code interpreter} on its arguments. Although the
95byte-code interpreter is not the same as the Lisp interpreter, it uses
96the same environment as the Lisp interpreter, and may on occasion invoke
97the Lisp interpreter. (@xref{Byte Compilation}.)
98
99 The details of what evaluation means for each kind of form are
100described below (@pxref{Forms}).
101
102@node Eval
103@section Eval
104
105 Most often, forms are evaluated automatically, by virtue of their
106occurrence in a program being run. On rare occasions, you may need to
107write code that evaluates a form that is computed at run time, such as
108after reading a form from text being edited or getting one from a
109property list. On these occasions, use the @code{eval} function.
110
111 The functions and variables described in this section evaluate
112forms, specify limits to the evaluation process, or record recently
113returned values. Loading a file also does evaluation
114(@pxref{Loading}).
115
116@defun eval form
117This is the basic function for performing evaluation. It evaluates
118@var{form} in the current environment and returns the result. How the
119evaluation proceeds depends on the type of the object (@pxref{Forms}).
120
121Since @code{eval} is a function, the argument expression that appears
122in a call to @code{eval} is evaluated twice: once as preparation before
123@code{eval} is called, and again by the @code{eval} function itself.
124Here is an example:
125
126@example
127@group
128(setq foo 'bar)
129 @result{} bar
130@end group
131@group
132(setq bar 'baz)
133 @result{} baz
134;; @r{@code{eval} receives argument @code{bar}, which is the value of @code{foo}}
135(eval foo)
136 @result{} baz
137@end group
138@end example
139
140The number of currently active calls to @code{eval} is limited to
141@code{max-lisp-eval-depth} (see below).
142@end defun
143
144@cindex evaluation of buffer contents
145@deffn Command eval-current-buffer &optional stream
146This function evaluates the forms in the current buffer. It reads
147forms from the buffer and calls @code{eval} on them until the end of the
148buffer is reached, or until an error is signaled and not handled.
149
150If @var{stream} is supplied, the variable @code{standard-output} is
151bound to @var{stream} during the evaluation (@pxref{Output
152Functions}).
153
154@code{eval-current-buffer} always returns @code{nil}.
155@end deffn
156
157@deffn Command eval-region start end &optional stream
158This function evaluates the forms in the current buffer in the region
159defined by the positions @var{start} and @var{end}. It reads forms from
160the region and calls @code{eval} on them until the end of the region is
161reached, or until an error is signaled and not handled.
162
163If @var{stream} is supplied, @code{standard-output} is bound to it
164for the duration of the command.
165
166@code{eval-region} always returns @code{nil}.
167@end deffn
168
169@defvar max-lisp-eval-depth
170This variable defines the maximum depth allowed in calls to @code{eval},
171@code{apply}, and @code{funcall} before an error is signaled (with error
172message @code{"Lisp nesting exceeds max-lisp-eval-depth"}). This counts
173calling the functions mentioned in Lisp expression, and recursive
174evaluation of function call arguments and function body forms.
175
176This limit, with the associated error when it is exceeded, is one way
177that Lisp avoids infinite recursion on an ill-defined function.
178@cindex Lisp nesting error
179
180The default value of this variable is 200. If you set it to a value
181less than 100, Lisp will reset it to 100 if the given value is reached.
182
183@code{max-specpdl-size} provides another limit on nesting.
184@xref{Local Variables}.
185@end defvar
186
187@defvar values
188The value of this variable is a list of the values returned by all the
189expressions which were read from buffers (including the minibuffer),
190evaluated, and printed. The elements are ordered most recent first.
191
192@example
193@group
194(setq x 1)
195 @result{} 1
196@end group
197@group
198(list 'A (1+ 2) auto-save-default)
199 @result{} (A 3 t)
200@end group
201@group
202values
203 @result{} ((A 3 t) 1 @dots{})
204@end group
205@end example
206
207This variable is useful for referring back to values of forms recently
208evaluated. It is generally a bad idea to print the value of
209@code{values} itself, since this may be very long. Instead, examine
210particular elements, like this:
211
212@example
213@group
214;; @r{Refer to the most recent evaluation result.}
215(nth 0 values)
216 @result{} (A 3 t)
217@end group
218@group
219;; @r{That put a new element on,}
220;; @r{so all elements move back one.}
221(nth 1 values)
222 @result{} (A 3 t)
223@end group
224@group
225;; @r{This gets the element that was next-to-last}
226;; @r{before this example.}
227(nth 3 values)
228 @result{} 1
229@end group
230@end example
231@end defvar
232
233@node Forms
234@section Kinds of Forms
235
236 A Lisp object that is intended to be evaluated is called a @dfn{form}.
237How Emacs evaluates a form depends on its data type. Emacs has three
238different kinds of form that are evaluated differently: symbols, lists,
239and ``all other types''. This section describes all three kinds,
240starting with ``all other types'' which are self-evaluating forms.
241
242@menu
243* Self-Evaluating Forms:: Forms that evaluate to themselves.
244* Symbol Forms:: Symbols evaluate as variables.
245* Classifying Lists:: How to distinguish various sorts of list forms.
246* Function Indirection:: When a symbol appears as the car of a list,
247 we find the real function via the symbol.
248* Function Forms:: Forms that call functions.
249* Macro Forms:: Forms that call macros.
250* Special Forms:: ``Special forms'' are idiosyncratic primitives,
251 most of them extremely important.
252* Autoloading:: Functions set up to load files
253 containing their real definitions.
254@end menu
255
256@node Self-Evaluating Forms
257@subsection Self-Evaluating Forms
258@cindex vector evaluation
259@cindex literal evaluation
260@cindex self-evaluating form
261
262 A @dfn{self-evaluating form} is any form that is not a list or symbol.
263Self-evaluating forms evaluate to themselves: the result of evaluation
264is the same object that was evaluated. Thus, the number 25 evaluates to
26525, and the string @code{"foo"} evaluates to the string @code{"foo"}.
266Likewise, evaluation of a vector does not cause evaluation of the
267elements of the vector---it returns the same vector with its contents
268unchanged.
269
270@example
271@group
272'123 ; @r{An object, shown without evaluation.}
273 @result{} 123
274@end group
275@group
276123 ; @r{Evaluated as usual---result is the same.}
277 @result{} 123
278@end group
279@group
280(eval '123) ; @r{Evaluated ``by hand''---result is the same.}
281 @result{} 123
282@end group
283@group
284(eval (eval '123)) ; @r{Evaluating twice changes nothing.}
285 @result{} 123
286@end group
287@end example
288
289 It is common to write numbers, characters, strings, and even vectors
290in Lisp code, taking advantage of the fact that they self-evaluate.
291However, it is quite unusual to do this for types that lack a read
292syntax, because there's no way to write them textually; however, it is
293possible to construct Lisp expressions containing these types by means
294of a Lisp program. Here is an example:
295
296@example
297@group
298;; @r{Build an expression containing a buffer object.}
299(setq buffer (list 'print (current-buffer)))
300 @result{} (print #<buffer eval.texi>)
301@end group
302@group
303;; @r{Evaluate it.}
304(eval buffer)
305 @print{} #<buffer eval.texi>
306 @result{} #<buffer eval.texi>
307@end group
308@end example
309
310@node Symbol Forms
311@subsection Symbol Forms
312@cindex symbol evaluation
313
314 When a symbol is evaluated, it is treated as a variable. The result
315is the variable's value, if it has one. If it has none (if its value
316cell is void), an error is signaled. For more information on the use of
317variables, see @ref{Variables}.
318
319 In the following example, we set the value of a symbol with
320@code{setq}. Then we evaluate the symbol, and get back the value that
321@code{setq} stored.
322
323@example
324@group
325(setq a 123)
326 @result{} 123
327@end group
328@group
329(eval 'a)
330 @result{} 123
331@end group
332@group
333a
334 @result{} 123
335@end group
336@end example
337
338 The symbols @code{nil} and @code{t} are treated specially, so that the
339value of @code{nil} is always @code{nil}, and the value of @code{t} is
340always @code{t}. Thus, these two symbols act like self-evaluating
341forms, even though @code{eval} treats them like any other symbol.
342
343@node Classifying Lists
344@subsection Classification of List Forms
345@cindex list form evaluation
346
347 A form that is a nonempty list is either a function call, a macro
348call, or a special form, according to its first element. These three
349kinds of forms are evaluated in different ways, described below. The
350remaining list elements constitute the @dfn{arguments} for the function,
351macro, or special form.
352
353 The first step in evaluating a nonempty list is to examine its first
354element. This element alone determines what kind of form the list is
355and how the rest of the list is to be processed. The first element is
356@emph{not} evaluated, as it would be in some Lisp dialects such as
357Scheme.
358
359@node Function Indirection
360@subsection Symbol Function Indirection
361@cindex symbol function indirection
362@cindex indirection
363@cindex void function
364
365 If the first element of the list is a symbol then evaluation examines
366the symbol's function cell, and uses its contents instead of the
367original symbol. If the contents are another symbol, this process,
368called @dfn{symbol function indirection}, is repeated until it obtains a
369non-symbol. @xref{Function Names}, for more information about using a
370symbol as a name for a function stored in the function cell of the
371symbol.
372
373 One possible consequence of this process is an infinite loop, in the
374event that a symbol's function cell refers to the same symbol. Or a
375symbol may have a void function cell, in which case the subroutine
376@code{symbol-function} signals a @code{void-function} error. But if
377neither of these things happens, we eventually obtain a non-symbol,
378which ought to be a function or other suitable object.
379
380@kindex invalid-function
381@cindex invalid function
382 More precisely, we should now have a Lisp function (a lambda
383expression), a byte-code function, a primitive function, a Lisp macro, a
384special form, or an autoload object. Each of these types is a case
385described in one of the following sections. If the object is not one of
386these types, the error @code{invalid-function} is signaled.
387
388 The following example illustrates the symbol indirection process. We
389use @code{fset} to set the function cell of a symbol and
390@code{symbol-function} to get the function cell contents
391(@pxref{Function Cells}). Specifically, we store the symbol @code{car}
392into the function cell of @code{first}, and the symbol @code{first} into
393the function cell of @code{erste}.
394
395@smallexample
396@group
397;; @r{Build this function cell linkage:}
398;; ------------- ----- ------- -------
399;; | #<subr car> | <-- | car | <-- | first | <-- | erste |
400;; ------------- ----- ------- -------
401@end group
402@end smallexample
403
404@smallexample
405@group
406(symbol-function 'car)
407 @result{} #<subr car>
408@end group
409@group
410(fset 'first 'car)
411 @result{} car
412@end group
413@group
414(fset 'erste 'first)
415 @result{} first
416@end group
417@group
418(erste '(1 2 3)) ; @r{Call the function referenced by @code{erste}.}
419 @result{} 1
420@end group
421@end smallexample
422
423 By contrast, the following example calls a function without any symbol
424function indirection, because the first element is an anonymous Lisp
425function, not a symbol.
426
427@smallexample
428@group
429((lambda (arg) (erste arg))
430 '(1 2 3))
431 @result{} 1
432@end group
433@end smallexample
434
435@noindent
436After that function is called, its body is evaluated; this does
437involve symbol function indirection when calling @code{erste}.
438
439 The built-in function @code{indirect-function} provides an easy way to
440perform symbol function indirection explicitly.
441
442@c Emacs 19 feature
443@defun indirect-function function
444This function returns the meaning of @var{function} as a function. If
445@var{function} is a symbol, then it finds @var{function}'s function
446definition and starts over with that value. If @var{function} is not a
447symbol, then it returns @var{function} itself.
448
449Here is how you could define @code{indirect-function} in Lisp:
450
451@smallexample
452(defun indirect-function (function)
453 (if (symbolp function)
454 (indirect-function (symbol-function function))
455 function))
456@end smallexample
457@end defun
458
459@node Function Forms
460@subsection Evaluation of Function Forms
461@cindex function form evaluation
462@cindex function call
463
464 If the first element of a list being evaluated is a Lisp function
465object, byte-code object or primitive function object, then that list is
466a @dfn{function call}. For example, here is a call to the function
467@code{+}:
468
469@example
470(+ 1 x)
471@end example
472
473 The first step ni evaluating a function call is to evaluate the
474remaining elements of the list in the order they appear. The results
475are the actual argument values, one value for each list element. The
476next step is to call the function with this list of arguments,
477effectively using the function @code{apply} (@pxref{Calling Functions}).
478If the function is written in Lisp, the arguments are used to bind the
479argument variables of the function (@pxref{Lambda Expressions}); then
480the forms in the function body are evaluated in order, and the value of
481the last body form becomes the value of the function call.
482
483@node Macro Forms
484@subsection Lisp Macro Evaluation
485@cindex macro call evaluation
486
487 If the first element of a list being evaluated is a macro object, then
488the list is a @dfn{macro call}. When a macro call is evaluated, the
489elements of the rest of the list are @emph{not} initially evaluated.
490Instead, these elements themselves are used as the arguments of the
491macro. The macro definition computes a replacement form, called the
492@dfn{expansion} of the macro, to be evaluated in place of the original
493form. The expansion may be any sort of form: a self-evaluating
494constant, a symbol or a list. If the expansion is itself a macro call,
495this process of expansion repeats until some other sort of form results.
496
497 Normally, the argument expressions are not evaluated as part of
498computing the macro expansion, but instead appear as part of the
499expansion, so they are evaluated when the expansion is evaluated.
500
501 For example, given a macro defined as follows:
502
503@example
504@group
505(defmacro cadr (x)
506 (list 'car (list 'cdr x)))
507@end group
508@end example
509
510@noindent
511an expression such as @code{(cadr (assq 'handler list))} is a macro
512call, and its expansion is:
513
514@example
515(car (cdr (assq 'handler list)))
516@end example
517
518@noindent
519Note that the argument @code{(assq 'handler list)} appears in the
520expansion.
521
522@xref{Macros}, for a complete description of Emacs Lisp macros.
523
524@node Special Forms
525@subsection Special Forms
526@cindex special form evaluation
527
528 A @dfn{special form} is a primitive function specially marked so that
529its arguments are not all evaluated. Most special forms define control
530structures or perform variable bindings---things which functions cannot
531do.
532
533 Each special form has its own rules for which arguments are evaluated
534and which are used without evaluation. Whether a particular argument is
535evaluated may depend on the results of evaluating other arguments.
536
537 Here is a list, in alphabetical order, of all of the special forms in
538Emacs Lisp with a reference to where each is described.
539
540@table @code
541@item and
542@pxref{Combining Conditions}
543
544@item catch
545@pxref{Catch and Throw}
546
547@item cond
548@pxref{Conditionals}
549
550@item condition-case
551@pxref{Handling Errors}
552
553@item defconst
554@pxref{Defining Variables}
555
556@item defmacro
557@pxref{Defining Macros}
558
559@item defun
560@pxref{Defining Functions}
561
562@item defvar
563@pxref{Defining Variables}
564
565@item function
566@pxref{Anonymous Functions}
567
568@item if
569@pxref{Conditionals}
570
571@item interactive
572@pxref{Interactive Call}
573
574@item let
575@itemx let*
576@pxref{Local Variables}
577
578@item or
579@pxref{Combining Conditions}
580
581@item prog1
582@itemx prog2
583@itemx progn
584@pxref{Sequencing}
585
586@item quote
587@pxref{Quoting}
588
589@item save-excursion
590@pxref{Excursions}
591
592@item save-restriction
593@pxref{Narrowing}
594
595@item save-window-excursion
596@pxref{Window Configurations}
597
598@item setq
599@pxref{Setting Variables}
600
601@item setq-default
602@pxref{Creating Buffer-Local}
603
604@item track-mouse
605@pxref{Mouse Tracking}
606
607@item unwind-protect
608@pxref{Nonlocal Exits}
609
610@item while
611@pxref{Iteration}
612
613@item with-output-to-temp-buffer
614@pxref{Temporary Displays}
615@end table
616
617@cindex CL note---special forms compared
618@quotation
619@b{Common Lisp note:} here are some comparisons of special forms in
620GNU Emacs Lisp and Common Lisp. @code{setq}, @code{if}, and
621@code{catch} are special forms in both Emacs Lisp and Common Lisp.
622@code{defun} is a special form in Emacs Lisp, but a macro in Common
623Lisp. @code{save-excursion} is a special form in Emacs Lisp, but
624doesn't exist in Common Lisp. @code{throw} is a special form in
625Common Lisp (because it must be able to throw multiple values), but it
626is a function in Emacs Lisp (which doesn't have multiple
627values).@refill
628@end quotation
629
630@node Autoloading
631@subsection Autoloading
632
633 The @dfn{autoload} feature allows you to call a function or macro
634whose function definition has not yet been loaded into Emacs. It
635specifies which file contains the definition. When an autoload object
636appears as a symbol's function definition, calling that symbol as a
637function automatically loads the specified file; then it calls the real
638definition loaded from that file. @xref{Autoload}.
639
640@node Quoting
641@section Quoting
642@cindex quoting
643
644 The special form @code{quote} returns its single argument
645``unchanged''.
646
647@defspec quote object
648This special form returns @var{object}, without evaluating it. This
649provides a way to include constant symbols and lists, which are not
650self-evaluating objects, in a program. (It is not necessary to quote
651self-evaluating objects such as numbers, strings, and vectors.)
652
653@cindex @samp{'} for quoting
654@cindex quoting using apostrophe
655@cindex apostrophe for quoting
656Because @code{quote} is used so often in programs, Lisp provides a
657convenient read syntax for it. An apostrophe character (@samp{'})
658followed by a Lisp object (in read syntax) expands to a list whose first
659element is @code{quote}, and whose second element is the object. Thus,
660the read syntax @code{'x} is an abbreviation for @code{(quote x)}.
661
662Here are some examples of expressions that use @code{quote}:
663
664@example
665@group
666(quote (+ 1 2))
667 @result{} (+ 1 2)
668@end group
669@group
670(quote foo)
671 @result{} foo
672@end group
673@group
674'foo
675 @result{} foo
676@end group
677@group
678''foo
679 @result{} (quote foo)
680@end group
681@group
682'(quote foo)
683 @result{} (quote foo)
684@end group
685@group
686['foo]
687 @result{} [(quote foo)]
688@end group
689@end example
690@end defspec
691
692 Other quoting constructs include @code{function} (@pxref{Anonymous
693Functions}), which causes an anonymous lambda expression written in Lisp
694to be compiled, and @code{`} (@pxref{Backquote}), which is used to quote
695only part of a list, while computing and substituting other parts.
diff --git a/lispref/keymaps.texi b/lispref/keymaps.texi
new file mode 100644
index 00000000000..298397e55ac
--- /dev/null
+++ b/lispref/keymaps.texi
@@ -0,0 +1,1638 @@
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/keymaps
6@node Keymaps, Modes, Command Loop, Top
7@chapter Keymaps
8@cindex keymap
9
10 The bindings between input events and commands are recorded in data
11structures called @dfn{keymaps}. Each binding in a keymap associates
12(or @dfn{binds}) an individual event type either with another keymap or
13with a command. When an event is bound to a keymap, that keymap is
14used to look up the next input event; this continues until a command
15is found. The whole process is called @dfn{key lookup}.
16
17@menu
18* Keymap Terminology:: Definitions of terms pertaining to keymaps.
19* Format of Keymaps:: What a keymap looks like as a Lisp object.
20* Creating Keymaps:: Functions to create and copy keymaps.
21* Inheritance and Keymaps:: How one keymap can inherit the bindings
22 of another keymap.
23* Prefix Keys:: Defining a key with a keymap as its definition.
24* Menu Keymaps:: A keymap can define a menu.
25* Active Keymaps:: Each buffer has a local keymap
26 to override the standard (global) bindings.
27 A minor mode can also override them.
28* Key Lookup:: How extracting elements from keymaps works.
29* Functions for Key Lookup:: How to request key lookup.
30* Changing Key Bindings:: Redefining a key in a keymap.
31* Key Binding Commands:: Interactive interfaces for redefining keys.
32* Scanning Keymaps:: Looking through all keymaps, for printing help.
33@end menu
34
35@node Keymap Terminology
36@section Keymap Terminology
37@cindex key
38@cindex keystroke
39@cindex key binding
40@cindex binding of a key
41@cindex complete key
42@cindex undefined key
43
44 A @dfn{keymap} is a table mapping event types to definitions (which
45can be any Lisp objects, though only certain types are meaningful for
46execution by the command loop). Given an event (or an event type) and a
47keymap, Emacs can get the event's definition. Events include ordinary
48@sc{ASCII} characters, function keys, and mouse actions (@pxref{Input
49Events}).
50
51 A sequence of input events that form a unit is called a
52@dfn{key sequence}, or @dfn{key} for short. A sequence of one event
53is always a key sequence, and so are some multi-event sequences.
54
55 A keymap determines a binding or definition for any key sequence. If
56the key sequence is a single event, its binding is the definition of the
57event in the keymap. The binding of a key sequence of more than one
58event is found by an iterative process: the binding of the first event
59is found, and must be a keymap; then the second event's binding is found
60in that keymap, and so on until all the events in the key sequence are
61used up.
62
63 If the binding of a key sequence is a keymap, we call the key sequence
64a @dfn{prefix key}. Otherwise, we call it a @dfn{complete key} (because
65no more characters can be added to it). If the binding is @code{nil},
66we call the key @dfn{undefined}. Examples of prefix keys are @kbd{C-c},
67@kbd{C-x}, and @kbd{C-x 4}. Examples of defined complete keys are
68@kbd{X}, @key{RET}, and @kbd{C-x 4 C-f}. Examples of undefined complete
69keys are @kbd{C-x C-g}, and @kbd{C-c 3}. @xref{Prefix Keys}, for more
70details.
71
72 The rule for finding the binding of a key sequence assumes that the
73intermediate bindings (found for the events before the last) are all
74keymaps; if this is not so, the sequence of events does not form a
75unit---it is not really a key sequence. In other words, removing one or
76more events from the end of any valid key must always yield a prefix
77key. For example, @kbd{C-f C-f} is not a key; @kbd{C-f} is not a prefix
78key, so a longer sequence starting with @kbd{C-f} cannot be a key.
79
80 Note that the set of possible multi-event key sequences depends on the
81bindings for prefix keys; therefore, it can be different for different
82keymaps, and can change when bindings are changed. However, a one-event
83sequence is always a key sequence, because it does not depend on any
84prefix keys for its well-formedness.
85
86 At any time, several primary keymaps are @dfn{active}---that is, in
87use for finding key bindings. These are the @dfn{global map}, which is
88shared by all buffers; the @dfn{local keymap}, which is usually
89associated with a specific major mode; and zero or more @dfn{minor mode
90keymaps} which belong to currently enabled minor modes. (Not all minor
91modes have keymaps.) The local keymap bindings shadow (i.e., take
92precedence over) the corresponding global bindings. The minor mode
93keymaps shadow both local and global keymaps. @xref{Active Keymaps},
94for details.
95
96@node Format of Keymaps
97@section Format of Keymaps
98@cindex format of keymaps
99@cindex keymap format
100@cindex full keymap
101@cindex sparse keymap
102
103 A keymap is a list whose @sc{car} is the symbol @code{keymap}. The
104remaining elements of the list define the key bindings of the keymap.
105Use the function @code{keymapp} (see below) to test whether an object is
106a keymap.
107
108 An ordinary element is a cons cell of the form @code{(@var{type} .@:
109@var{binding})}. This specifies one binding which applies to events of
110type @var{type}. Each ordinary binding applies to events of a
111particular @dfn{event type}, which is always a character or a symbol.
112@xref{Classifying Events}.
113
114@cindex default key binding
115@c Emacs 19 feature
116 A cons cell whose @sc{car} is @code{t} is a @dfn{default key binding};
117any event not bound by other elements of the keymap is given
118@var{binding} as its binding. Default bindings allow a keymap to bind
119all possible event types without having to enumerate all of them. A
120keymap that has a default binding completely masks any lower-precedence
121keymap.
122
123 If an element of a keymap is a vector, the vector counts as bindings
124for all the @sc{ASCII} characters; vector element @var{n} is the binding
125for the character with code @var{n}. This is a more compact way to
126record lots of bindings. A keymap with such a vector is called a
127@dfn{full keymap}. Other keymaps are called @dfn{sparse keymaps}.
128
129 When a keymap contains a vector, it always defines a binding for every
130@sc{ASCII} character even if the vector element is @code{nil}. Such a
131binding of @code{nil} overrides any default binding in the keymap.
132However, default bindings are still meaningful for events that are not
133@sc{ASCII} characters. A binding of @code{nil} does @emph{not}
134override lower-precedence keymaps; thus, if the local map gives a
135binding of @code{nil}, Emacs uses the binding from the global map.
136
137@cindex keymap prompt string
138@cindex overall prompt string
139@cindex prompt string of keymap
140 Aside from bindings, a keymap can also have a string as an element.
141This is called the @dfn{overall prompt string} and makes it possible to
142use the keymap as a menu. @xref{Menu Keymaps}.
143
144@cindex meta characters lookup
145 Keymaps do not directly record bindings for the meta characters, whose
146codes are from 128 to 255. Instead, meta characters are regarded for
147purposes of key lookup as sequences of two characters, the first of
148which is @key{ESC} (or whatever is currently the value of
149@code{meta-prefix-char}). Thus, the key @kbd{M-a} is really represented
150as @kbd{@key{ESC} a}, and its global binding is found at the slot for
151@kbd{a} in @code{esc-map} (@pxref{Prefix Keys}).
152
153 Here as an example is the local keymap for Lisp mode, a sparse
154keymap. It defines bindings for @key{DEL} and @key{TAB}, plus @kbd{C-c
155C-l}, @kbd{M-C-q}, and @kbd{M-C-x}.
156
157@example
158@group
159lisp-mode-map
160@result{}
161@end group
162@group
163(keymap
164 ;; @key{TAB}
165 (9 . lisp-indent-line)
166@end group
167@group
168 ;; @key{DEL}
169 (127 . backward-delete-char-untabify)
170@end group
171@group
172 (3 keymap
173 ;; @kbd{C-c C-l}
174 (12 . run-lisp))
175@end group
176@group
177 (27 keymap
178 ;; @r{@kbd{M-C-q}, treated as @kbd{@key{ESC} C-q}}
179 (17 . indent-sexp)
180 ;; @r{@kbd{M-C-x}, treated as @kbd{@key{ESC} C-x}}
181 (24 . lisp-send-defun)))
182@end group
183@end example
184
185@defun keymapp object
186This function returns @code{t} if @var{object} is a keymap, @code{nil}
187otherwise. Practically speaking, this function tests for a list whose
188@sc{car} is @code{keymap}.
189
190@example
191@group
192(keymapp '(keymap))
193 @result{} t
194@end group
195@group
196(keymapp (current-global-map))
197 @result{} t
198@end group
199@end example
200@end defun
201
202@node Creating Keymaps
203@section Creating Keymaps
204@cindex creating keymaps
205
206 Here we describe the functions for creating keymaps.
207
208@defun make-keymap &optional prompt
209This function creates and returns a new full keymap (i.e., one which
210contains a vector of length 128 for defining all the @sc{ASCII}
211characters). The new keymap initially binds all @sc{ASCII} characters
212to @code{nil}, and does not bind any other kind of event.
213
214@example
215@group
216(make-keymap)
217 @result{} (keymap [nil nil nil @dots{} nil nil])
218@end group
219@end example
220
221If you specify @var{prompt}, that becomes the overall prompt string for
222the keymap. The prompt string is useful for menu keymaps (@pxref{Menu
223Keymaps}).
224@end defun
225
226@defun make-sparse-keymap &optional prompt
227This function creates and returns a new sparse keymap with no entries.
228The new keymap does not bind any events. The argument @var{prompt}
229specifies a prompt string, as in @code{make-keymap}.
230
231@example
232@group
233(make-sparse-keymap)
234 @result{} (keymap)
235@end group
236@end example
237@end defun
238
239@defun copy-keymap keymap
240This function returns a copy of @var{keymap}. Any keymaps which
241appear directly as bindings in @var{keymap} are also copied recursively,
242and so on to any number of levels. However, recursive copying does not
243take place when the definition of a character is a symbol whose function
244definition is a keymap; the same symbol appears in the new copy.
245@c Emacs 19 feature
246
247@example
248@group
249(setq map (copy-keymap (current-local-map)))
250@result{} (keymap
251@end group
252@group
253 ;; @r{(This implements meta characters.)}
254 (27 keymap
255 (83 . center-paragraph)
256 (115 . center-line))
257 (9 . tab-to-tab-stop))
258@end group
259
260@group
261(eq map (current-local-map))
262 @result{} nil
263@end group
264@group
265(equal map (current-local-map))
266 @result{} t
267@end group
268@end example
269@end defun
270
271@node Inheritance and Keymaps
272@section Inheritance and Keymaps
273@cindex keymap inheritance
274@cindex inheriting a keymap's bindings
275
276 A keymap can inherit the bindings of another keymap. Do do this, make
277a keymap whose ``tail'' is another existing keymap to inherit from.
278Such a keymap looks like this:
279
280@example
281(keymap @var{bindings}@dots{} . @var{other-keymap})
282@end example
283
284@noindent
285The effect is that this keymap inherits all the bindings of
286@var{other-keymap}, whatever they may be at the time a key is looked up,
287but can add to them or override them with @var{bindings}.
288
289If you change the bindings in @var{other-keymap} using @code{define-key}
290or other key-binding functions, these changes are visible in the
291inheriting keymap unless shadowed by @var{bindings}. The converse is
292not true: if you use @code{define-key} to change the inheriting keymap,
293that affects @var{bindings}, but has no effect on @var{other-keymap}.
294
295Here is an example showing how to make a keymap that inherits
296from @code{text-mode-map}:
297
298@example
299(setq my-mode-map (cons 'keymap text-mode-map))
300@end example
301
302@node Prefix Keys
303@section Prefix Keys
304@cindex prefix key
305
306 A @dfn{prefix key} has an associated keymap which defines what to do
307with key sequences that start with the prefix key. For example,
308@kbd{C-x} is a prefix key, and it uses a keymap which is also stored in
309the variable @code{ctl-x-map}. Here is a list of the standard prefix
310keys of Emacs and their keymaps:
311
312@itemize @bullet
313@item
314@vindex esc-map
315@findex ESC-prefix
316@code{esc-map} is used for events that follow @key{ESC}. Thus, the
317global definitions of all meta characters are actually found here. This
318map is also the function definition of @code{ESC-prefix}.
319
320@item
321@cindex @kbd{C-h}
322@code{help-map} is used for events that follow @kbd{C-h}.
323
324@item
325@cindex @kbd{C-c}
326@vindex mode-specific-map
327@code{mode-specific-map} is for events that follow @kbd{C-c}. This
328map is not actually mode specific; its name was chosen to be informative
329for the user in @kbd{C-h b} (@code{display-bindings}), where it
330describes the main use of the @kbd{C-c} prefix key.
331
332@item
333@cindex @kbd{C-x}
334@vindex ctl-x-map
335@findex Control-X-prefix
336@code{ctl-x-map} is the variable name for the map used for events
337that follow @kbd{C-x}. This map is also the function definition of
338@code{Control-X-prefix}.
339
340@item
341@cindex @kbd{C-x 4}
342@vindex ctl-x-4-map
343@code{ctl-x-4-map} is used for events that follow @kbd{C-x 4}.
344
345@c Emacs 19 feature
346@item
347@cindex @kbd{C-x 5}
348@vindex ctl-x-5-map
349@code{ctl-x-5-map} used is for events that follow @kbd{C-x 5}.
350
351@c Emacs 19 feature
352@item
353@cindex @kbd{C-x n}
354@cindex @kbd{C-x r}
355@cindex @kbd{C-x a}
356The prefix keys @kbd{C-x n}, @kbd{C-x r} and @kbd{C-x a} use keymaps
357that have no special name.
358@end itemize
359
360 The binding of a prefix key is the keymap to use for looking up the
361events that follow the prefix key. (It may instead be a symbol whose
362function definition is a keymap. The effect is the same, but the symbol
363serves as a name for the prefix key.) Thus, the binding of @kbd{C-x} is
364the symbol @code{Control-X-prefix}, whose function definition is the
365keymap for @kbd{C-x} commands. (The same keymap is also the value of
366@code{ctl-x-map}.)
367
368 Prefix key definitions of this sort can appear in any active keymap.
369The definitions of @kbd{C-c}, @kbd{C-x}, @kbd{C-h} and @key{ESC} as
370prefix keys appear in the global map, so these prefix keys are always
371available. Major and minor modes can redefine a key as a prefix by
372putting a prefix key definition for it in the local map or the minor
373mode's map. @xref{Active Keymaps}.
374
375 If a key is defined as a prefix in more than one active map, then its
376various definitions are in effect merged: the commands defined in the
377minor mode keymaps come first, followed by those in the local map's
378prefix definition, and then by those from the global map.
379
380 In the following example, we make @kbd{C-p} a prefix key in the local
381keymap, in such a way that @kbd{C-p} is identical to @kbd{C-x}. Then
382the binding for @kbd{C-p C-f} is the function @code{find-file}, just
383like @kbd{C-x C-f}. The key sequence @kbd{C-p 6} is not found in any
384active keymap.
385
386@example
387@group
388(use-local-map (make-sparse-keymap))
389 @result{} nil
390@end group
391@group
392(local-set-key "\C-p" ctl-x-map)
393 @result{} nil
394@end group
395@group
396(key-binding "\C-p\C-f")
397 @result{} find-file
398@end group
399
400@group
401(key-binding "\C-p6")
402 @result{} nil
403@end group
404@end example
405
406@defun define-prefix-command symbol
407@cindex prefix command
408 This function defines @var{symbol} as a prefix command: it creates a
409full keymap and stores it as @var{symbol}'s function definition.
410Storing the symbol as the binding of a key makes the key a prefix key
411which has a name. It also sets @var{symbol} as a variable, to have the
412keymap as its value. The function returns @var{symbol}.
413
414 In Emacs version 18, only the function definition of @var{symbol} was
415set, not the value as a variable.
416@end defun
417
418@node Menu Keymaps
419@section Menu Keymaps
420@cindex menu keymaps
421
422@c Emacs 19 feature
423A keymap can define a menu as well as bindings for keyboard keys and
424mouse button. Menus are usually actuated with the mouse, but they can
425work with the keyboard also.
426
427@menu
428* Defining Menus:: How to make a keymap that defines a menu.
429* Mouse Menus:: How users actuate the menu with the mouse.
430* Keyboard Menus:: How they actuate it with the keyboard.
431* Menu Example:: Making a simple menu.
432* Menu Bar:: How to customize the menu bar.
433* Modifying Menus:: How to add new items to a menu.
434@end menu
435
436@node Defining Menus
437@subsection Defining Menus
438@cindex defining menus
439@cindex menu prompt string
440@cindex prompt string (of menu)
441
442A keymap is suitable for menu use if it has an @dfn{overall prompt
443string}, which is a string that appears as an element of the keymap.
444(@xref{Format of Keymaps}.) The string should describe the purpose of
445the menu. The easiest way to construct a keymap with a prompt string is
446to specify the string as an argument when you call @code{make-keymap} or
447@code{make-sparse-keymap} (@pxref{Creating Keymaps}).
448
449The individual bindings in the menu keymap should have item
450strings; these strings become the items displayed in the menu. A
451binding with a item string looks like this:
452
453@example
454(@var{string} . @var{real-binding})
455@end example
456
457The item string for a binding should be short---one or two words. It
458should describe the action of the command it corresponds to.
459
460As far as @code{define-key} is concerned, @var{string} is part of the
461event's binding. However, @code{lookup-key} returns just
462@var{real-binding}, and only @var{real-binding} is used for executing
463the key.
464
465You can also supply a second string, called the help string, as follows:
466
467@example
468(@var{string} @var{help-string} . @var{real-binding})
469@end example
470
471Currently Emacs does not actually use @var{help-string}; it knows only
472how to ignore @var{help-string} in order to extract @var{real-binding}.
473In the future we hope to make @var{help-string} serve as extended
474documentation for the menu item, available on request.
475
476If @var{real-binding} is @code{nil}, then @var{string} appears in the
477menu but cannot be selected.
478
479If @var{real-binding} is a symbol, and has a non-@code{nil}
480@code{menu-enable} property, that property is an expression which
481controls whether the menu item is enabled. Every time the keymap is
482used to display a menu, Emacs evaluates the expression, and it enables
483the menu item only if the expression's value is non-@code{nil}. When a
484menu item is disabled, it is displayed in a ``fuzzy'' fashion, and
485cannot be selected with the mouse.
486
487The order of items in the menu is the same as the order of bindings in
488the keymap. Since @code{define-key} puts new bindings at the front, you
489should define the menu items starting at the bottom of the menu and
490moving to the top, if you care about the order. When you add an item to
491an existing menu, you can specify its position in the menu using
492@code{define-key-after} (@pxref{Modifying Menus}).
493
494You've probably noticed that menu items show the equivalent keyboard key
495sequence (if any) to invoke the same command. To save time on
496recalculation, menu display caches this information in a sublist in the
497binding, like this:
498
499@c This line is not too long--rms.
500@example
501(@var{string} @r{[}@var{help-string}@r{]} (@var{key-binding-data}) . @var{real-binding})
502@end example
503
504Don't put these sublists in the menu item yourself; menu display
505calculates them automatically. Don't add keyboard equivalents to the
506item string yourself, for that is redundant.
507
508@node Mouse Menus
509@subsection Menus and the Mouse
510
511The way to make a menu keymap produce a menu is to make it the
512definition of a prefix key.
513
514If the prefix key ends with a mouse event, Emacs handles the menu keymap
515by popping up a visible menu, so that the user can select a choice with
516the mouse. When the user clicks on a menu item, the event generated is
517whatever character or symbol has the binding which brought about that
518menu item. (A menu item may generate a series of events if the menu has
519multiple levels or comes from the menu bar.)
520
521It's often best to use a button-down event to trigger the menu. Then
522the user can select a menu item by releasing the button.
523
524A single keymap can appear as multiple menu panes, if you explicitly
525arrange for this. The way to do this is to make a keymap for each pane,
526then create a binding for each of those maps in the main keymap of the
527menu. Give each of these bindings a item string that starts with
528@samp{@@}. The rest of the item string becomes the name of the pane.
529See the file @file{lisp/mouse.el} for an example of this. Any ordinary
530bindings with @samp{@@}-less item strings are grouped into one pane,
531which appears along with the other panes explicitly created for the
532submaps.
533
534X toolkit menus don't have panes; instead, they can have submenus.
535Every nested keymap becomes a submenu, whether the item string starts
536with @samp{@@} or not. In a toolkit version of Emacs, The only thing
537special about @samp{@@} at the beginning of an item string is that the
538@samp{@@} doesn't appear in the menu item.
539
540You can also get multiple panes from separate keymaps. The full
541definition of a prefix key always comes from merging the definitions
542supplied by the various active keymaps (minor mode, local, and
543global). When more than one of these keymaps is a menu, each of them
544makes a separate pane or panes. @xref{Active Keymaps}.
545
546In toolkit versions of Emacs, menus don't have panes, so submenus are
547used to represent the separate keymaps. Each keymap's contribution
548becomes one submenu.
549
550A Lisp program can explicitly pop up a menu and receive the user's
551choice. You can use keymaps for this also. @xref{Pop-Up Menus}.
552
553@node Keyboard Menus
554@subsection Menus and the Keyboard
555
556When a prefix key ending with a keyboard event (a character or function
557key) has a definition that is a menu keymap, the user can use the
558keyboard to choose a menu item.
559
560Emacs displays the menu alternatives (the item strings of the
561bindings) in the echo area. If they don't all fit at once, the user can
562type @key{SPC} to see the next line of alternatives. Successive uses of
563@key{SPC} eventually get to the end of the menu and then cycle around to
564the beginning.
565
566When the user has found the desired alternative from the menu, he or she
567should type the corresponding character---the one whose binding is that
568alternative.
569
570In a menu intended for keyboard use, each menu item must clearly
571indicate what character to type. The best convention to use is to make
572the character the first letter of the item string. That is something
573users will understand without being told.
574
575This way of using menus in an Emacs-like editor was inspired by the
576Hierarkey system.
577
578@defvar menu-prompt-more-char
579This variable specifies the character to use to ask to see
580the next line of a menu. Its initial value is 32, the code
581for @key{SPC}.
582@end defvar
583
584@node Menu Example
585@subsection Menu Example
586
587 Here is a simple example of how to set up a menu for mouse use.
588
589@example
590(defvar my-menu-map
591 (make-sparse-keymap "Key Commands <==> Functions"))
592(fset 'help-for-keys my-menu-map)
593
594(define-key my-menu-map [bindings]
595 '("List all keystroke commands" . describe-bindings))
596(define-key my-menu-map [key]
597 '("Describe key briefly" . describe-key-briefly))
598(define-key my-menu-map [key-verbose]
599 '("Describe key verbose" . describe-key))
600(define-key my-menu-map [function]
601 '("Describe Lisp function" . describe-function))
602(define-key my-menu-map [where-is]
603 '("Where is this command" . where-is))
604
605(define-key global-map [C-S-down-mouse-1] 'help-for-keys)
606@end example
607
608 The symbols used in the key sequences bound in the menu are fictitious
609``function keys''; they don't appear on the keyboard, but that doesn't
610stop you from using them in the menu. Their names were chosen to be
611mnemonic, because they show up in the output of @code{where-is} and
612@code{apropos} to identify the corresponding menu items.
613
614 However, if you want the menu to be usable from the keyboard as well,
615you must bind real @sc{ASCII} characters as well as fictitious function
616keys.
617
618@node Menu Bar
619@subsection The Menu Bar
620@cindex menu bar
621
622 Most window systems allow each frame to have a @dfn{menu bar}---a
623permanently displayed menu stretching horizontally across the top of the
624frame. The items of the menu bar are the subcommands of the fake
625``function key'' @code{menu-bar}, as defined by all the active keymaps.
626
627 To add an item to the menu bar, invent a fake ``function key'' of your
628own (let's call it @var{key}), and make a binding for the key sequence
629@code{[menu-bar @var{key}]}. Most often, the binding is a menu keymap,
630so that pressing a button on the menu bar item leads to another menu.
631
632 When more than one active keymap defines the same fake function key
633for the menu bar, the item appears just once. If the user clicks on
634that menu bar item, it brings up a single, combined submenu containing
635all the subcommands of that item---the global subcommands, the local
636subcommands, and the minor mode subcommands, all together.
637
638 In order for a frame to display a menu bar, its @code{menu-bar-lines}
639parameter must be greater than zero. Emacs uses just one line for the
640menu bar itself; if you specify more than one line, the other lines
641serve to separate the menu bar from the windows in the frame. We
642recommend you try 1 or 2 as the value of @code{menu-bar-lines}. @xref{X
643Frame Parameters}.
644
645 Here's an example of setting up a menu bar item:
646
647@smallexample
648(modify-frame-parameters (selected-frame) '((menu-bar-lines . 2)))
649
650;; @r{Make a menu keymap (with a prompt string)}
651;; @r{and make it the menu bar item's definition.}
652(define-key global-map [menu-bar words]
653 (cons "Words" (make-sparse-keymap "Words")))
654
655@group
656;; @r{Define specific subcommands in the item's menu.}
657(define-key global-map
658 [menu-bar words forward]
659 '("Forward word" . forward-word))
660@end group
661@group
662(define-key global-map
663 [menu-bar words backward]
664 '("Backward word" . backward-word))
665@end group
666@end smallexample
667
668 A local keymap can cancel a menu bar item made by the global keymap by
669rebinding the same fake function key with @code{undefined} as the
670binding. For example, this is how Dired suppresses the @samp{Edit} menu
671bar item:
672
673@example
674(define-key dired-mode-map [menu-bar edit] 'undefined)
675@end example
676
677@noindent
678@code{edit} is the fake function key used by the global map for the
679@samp{Edit} menu bar item. The main reason to suppress a global
680menu bar item is to regain space for mode-specific items.
681
682@defvar menu-bar-final-items
683Normally the menu bar shows global items followed by items defined by the
684local maps.
685
686This variable holds a list of fake function keys for items to display at
687the end of the menu bar rather than in normal sequence. The default
688value is @code{(help)}; thus, the @samp{Help} menu item normally appears
689at the end of the menu bar, following local menu items.
690@end defvar
691
692@node Modifying Menus
693@subsection Modifying Menus
694
695 When you insert a new item in an existing menu, you probably want to
696put it in a particular place among the menu's existing items. If you
697use @code{define-key} to add the item, it normally goes at the front of
698the menu. To put it elsewhere, use @code{define-key-after}:
699
700@defun define-key-after map key binding after
701Define a binding in @var{map} for @var{key}, with value @var{binding},
702just like @code{define-key}, but position the binding in @var{map} after
703the binding for the key @var{after}. For example,
704
705@example
706(define-key-after my-menu [drink]
707 '("Drink" . drink-command) [eat])
708@end example
709
710@noindent
711makes a binding for the fake function key @key{drink} and puts it
712right after the binding for @key{eat}.
713@end defun
714
715@node Active Keymaps
716@section Active Keymaps
717@cindex active keymap
718@cindex global keymap
719@cindex local keymap
720
721 Emacs normally contains many keymaps; at any given time, just a few of
722them are @dfn{active} in that they participate in the interpretation
723of user input. These are the global keymap, the current buffer's
724local keymap, and the keymaps of any enabled minor modes.
725
726 The @dfn{global keymap} holds the bindings of keys that are defined
727regardless of the current buffer, such as @kbd{C-f}. The variable
728@code{global-map} holds this keymap, which is always active.
729
730 Each buffer may have another keymap, its @dfn{local keymap}, which may
731contain new or overriding definitions for keys. The current buffer's
732local keymap is always active except when @code{overriding-local-map}
733overrides it. Text properties can specify an alternative local map for
734certain parts of the buffer; see @ref{Special Properties}.
735
736 Each minor mode may have a keymap; if it does, the keymap is active
737when the minor mode is enabled.
738
739 The variable @code{overriding-local-map}, if non-@code{nil}, specifies
740another local keymap that overrides the buffer's local map and all the
741minor mode keymaps.
742
743 All the active keymaps are used together to determine what command to
744execute when a key is entered. Emacs searches these maps one by one, in
745order of decreasing precedence, until it finds a binding in one of the maps.
746
747 Normally, Emacs @emph{first} searches for the key in the minor mode
748maps (one map at a time); if they do not supply a binding for the key,
749Emacs searches the local map; if that too has no binding, Emacs then
750searches the global map. However, if @code{overriding-local-map} is
751non-@code{nil}, Emacs searches that map first, followed by the global
752map.
753
754 The procedure for searching a single keymap is called
755@dfn{key lookup}; see @ref{Key Lookup}.
756
757@cindex major mode keymap
758 Since every buffer that uses the same major mode normally uses the
759very same local keymap, it may appear as if the keymap is local to the
760mode. A change to the local keymap of a buffer (using
761@code{local-set-key}, for example) will be seen also in the other
762buffers that share that keymap.
763
764 The local keymaps that are used for Lisp mode, C mode, and several
765other major modes exist even if they have not yet been used. These
766local maps are the values of the variables @code{lisp-mode-map},
767@code{c-mode-map}, and so on. For most other modes, which are less
768frequently used, the local keymap is constructed only when the mode is
769used for the first time in a session.
770
771 The minibuffer has local keymaps, too; they contain various completion
772and exit commands. @xref{Intro to Minibuffers}.
773
774 @xref{Standard Keymaps}, for a list of standard keymaps.
775
776@defvar global-map
777 This variable contains the default global keymap that maps Emacs
778keyboard input to commands. The global keymap is normally this keymap.
779The default global keymap is a full keymap that binds
780@code{self-insert-command} to all of the printing characters.
781
782It is normal practice to change the bindings in the global map, but you
783should not assign this variable any value other than the keymap it starts
784out with.
785@end defvar
786
787@defun current-global-map
788 This function returns the current global keymap. This is the
789same as the value of @code{global-map} unless you change one or the
790other.
791
792@example
793@group
794(current-global-map)
795@result{} (keymap [set-mark-command beginning-of-line @dots{}
796 delete-backward-char])
797@end group
798@end example
799@end defun
800
801@defun current-local-map
802 This function returns the current buffer's local keymap, or @code{nil}
803if it has none. In the following example, the keymap for the
804@samp{*scratch*} buffer (using Lisp Interaction mode) is a sparse keymap
805in which the entry for @key{ESC}, @sc{ASCII} code 27, is another sparse
806keymap.
807
808@example
809@group
810(current-local-map)
811@result{} (keymap
812 (10 . eval-print-last-sexp)
813 (9 . lisp-indent-line)
814 (127 . backward-delete-char-untabify)
815@end group
816@group
817 (27 keymap
818 (24 . eval-defun)
819 (17 . indent-sexp)))
820@end group
821@end example
822@end defun
823
824@defun current-minor-mode-maps
825This function returns a list of the keymaps of currently enabled minor modes.
826@end defun
827
828@defun use-global-map keymap
829 This function makes @var{keymap} the new current global keymap. It
830returns @code{nil}.
831
832 It is very unusual to change the global keymap.
833@end defun
834
835@defun use-local-map keymap
836 This function makes @var{keymap} the new local keymap of the current
837buffer. If @var{keymap} is @code{nil}, then the buffer has no local
838keymap. @code{use-local-map} returns @code{nil}. Most major mode
839commands use this function.
840@end defun
841
842@c Emacs 19 feature
843@defvar minor-mode-map-alist
844This variable is an alist describing keymaps that may or may not be
845active according to the values of certain variables. Its elements look
846like this:
847
848@example
849(@var{variable} . @var{keymap})
850@end example
851
852The keymap @var{keymap} is active whenever @var{variable} has a
853non-@code{nil} value. Typically @var{variable} is the variable which
854enables or disables a minor mode. @xref{Keymaps and Minor Modes}.
855
856Note that elements of @code{minor-mode-map-alist} do not have the same
857structure as elements of @code{minor-mode-alist}. The map must be the
858@sc{cdr} of the element; a list with the map as the second element will
859not do.
860
861What's more, the keymap itself must appear in the @sc{cdr}. It does not
862work to store a variable in the @sc{cdr} and make the map the value of
863that variable.
864
865When more than one minor mode keymap is active, their order of priority
866is the order of @code{minor-mode-map-alist}. But you should design
867minor modes so that they don't interfere with each other. If you do
868this properly, the order will not matter.
869
870See also @code{minor-mode-key-binding} in @ref{Functions for Key
871Lookup}. See @ref{Keymaps and Minor Modes}, for more information about
872minor modes.
873@end defvar
874
875@defvar overriding-local-map
876If non-@code{nil}, a keymap to use instead of the buffer's local keymap
877and instead of all the minor mode keymaps. This keymap, if any,
878overrides all other maps that would have been active, except for the
879current global map.
880@end defvar
881
882@node Key Lookup
883@section Key Lookup
884@cindex key lookup
885@cindex keymap entry
886
887 @dfn{Key lookup} is the process of finding the binding of a key
888sequence from a given keymap. Actual execution of the binding is not
889part of key lookup.
890
891 Key lookup uses just the event types of each event in the key
892sequence; the rest of the event is ignored. In fact, a key sequence
893used for key lookup may designate mouse events with just their types
894(symbols) instead of with entire mouse events (lists). @xref{Input
895Events}. Such a pseudo-key-sequence is insufficient for
896@code{command-execute}, but it is sufficient for looking up or rebinding
897a key.
898
899 When the key sequence consists of multiple events, key lookup
900processes the events sequentially: the binding of the first event is
901found, and must be a keymap; then the second event's binding is found in
902that keymap, and so on until all the events in the key sequence are used
903up. (The binding thus found for the last event may or may not be a
904keymap.) Thus, the process of key lookup is defined in terms of a
905simpler process for looking up a single event in a keymap. How that is
906done depends on the type of object associated with the event in that
907keymap.
908
909 Let's use the term @dfn{keymap entry} to describe the value found by
910looking up an event type in a keymap. (This doesn't include the item
911string and other extra elements in menu key bindings because
912@code{lookup-key} and other key lookup functions don't include them in
913the returned value.) While any Lisp object may be stored in a keymap as
914a keymap entry, not all make sense for key lookup. Here is a list of
915the meaningful kinds of keymap entries:
916
917@table @asis
918@item @code{nil}
919@cindex @code{nil} in keymap
920@code{nil} means that the events used so far in the lookup form an
921undefined key. When a keymap fails to mention an event type at all, and
922has no default binding, that is equivalent to a binding of @code{nil}
923for that event type.
924
925@item @var{keymap}
926@cindex keymap in keymap
927The events used so far in the lookup form a prefix key. The next
928event of the key sequence is looked up in @var{keymap}.
929
930@item @var{command}
931@cindex command in keymap
932The events used so far in the lookup form a complete key,
933and @var{command} is its binding.
934
935@item @var{string}
936@itemx @var{vector}
937@cindex string in keymap
938The events used so far in the lookup form a complete key, whose
939binding is a keyboard macro. See @ref{Keyboard Macros}, for more
940information.
941
942@item @var{list}
943@cindex list in keymap
944The meaning of a list depends on the types of the elements of the list.
945
946@itemize @bullet
947@item
948If the @sc{car} of @var{list} is the symbol @code{keymap}, then the list
949is a keymap, and is treated as a keymap (see above).
950
951@item
952@cindex @code{lambda} in keymap
953If the @sc{car} of @var{list} is @code{lambda}, then the list is a
954lambda expression. This is presumed to be a command, and is treated as
955such (see above).
956
957@item
958If the @sc{car} of @var{list} is a keymap and the @sc{cdr} is an event
959type, then this is an @dfn{indirect entry}:
960
961@example
962(@var{othermap} . @var{othertype})
963@end example
964
965When key lookup encounters an indirect entry, it looks up instead the
966binding of @var{othertype} in @var{othermap} and uses that.
967
968This feature permits you to define one key as an alias for another key.
969For example, an entry whose @sc{car} is the keymap called @code{esc-map}
970and whose @sc{cdr} is 32 (the code for space) means, ``Use the global
971binding of @kbd{Meta-@key{SPC}}, whatever that may be.''
972@end itemize
973
974@item @var{symbol}
975@cindex symbol in keymap
976The function definition of @var{symbol} is used in place of
977@var{symbol}. If that too is a symbol, then this process is repeated,
978any number of times. Ultimately this should lead to an object which is
979a keymap, a command or a keyboard macro. A list is allowed if it is a
980keymap or a command, but indirect entries are not understood when found
981via symbols.
982
983Note that keymaps and keyboard macros (strings and vectors) are not
984valid functions, so a symbol with a keymap, string or vector as its
985function definition is also invalid as a function. It is, however,
986valid as a key binding. If the definition is a keyboard macro, then the
987symbol is also valid as an argument to @code{command-execute}
988(@pxref{Interactive Call}).
989
990@cindex @code{undefined} in keymap
991The symbol @code{undefined} is worth special mention: it means to treat
992the key as undefined. Strictly speaking, the key is defined, and its
993binding is the command @code{undefined}; but that command does the same
994thing that is done automatically for an undefined key: it rings the bell
995(by calling @code{ding}) but does not signal an error.
996
997@cindex preventing prefix key
998@code{undefined} is used in local keymaps to override a global key
999binding and make the key ``undefined'' locally. A local binding of
1000@code{nil} would fail to do this because it would not override the
1001global binding.
1002
1003@item @var{anything else}
1004If any other type of object is found, the events used so far in the
1005lookup form a complete key, and the object is its binding, but the
1006binding is not executable as a command.
1007@end table
1008
1009 In short, a keymap entry may be a keymap, a command, a keyboard macro,
1010a symbol which leads to one of them, or an indirection or @code{nil}.
1011Here is an example of a sparse keymap with two characters bound to
1012commands and one bound to another keymap. This map is the normal value
1013of @code{emacs-lisp-mode-map}. Note that 9 is the code for @key{TAB},
1014127 for @key{DEL}, 27 for @key{ESC}, 17 for @kbd{C-q} and 24 for
1015@kbd{C-x}.
1016
1017@example
1018@group
1019(keymap (9 . lisp-indent-line)
1020 (127 . backward-delete-char-untabify)
1021 (27 keymap (17 . indent-sexp) (24 . eval-defun)))
1022@end group
1023@end example
1024
1025@node Functions for Key Lookup
1026@section Functions for Key Lookup
1027
1028 Here are the functions and variables pertaining to key lookup.
1029
1030@defun lookup-key keymap key &optional accept-defaults
1031This function returns the definition of @var{key} in @var{keymap}. If
1032the string or vector @var{key} is not a valid key sequence according to
1033the prefix keys specified in @var{keymap} (which means it is ``too
1034long'' and has extra events at the end), then the value is a number, the
1035number of events at the front of @var{key} that compose a complete key.
1036
1037@c Emacs 19 feature
1038If @var{accept-defaults} is non-@code{nil}, then @code{lookup-key}
1039considers default bindings as well as bindings for the specific events
1040in @var{key}. Otherwise, @code{lookup-key} reports only bindings for
1041the specific sequence @var{key}, ignoring default bindings except when
1042an element of @var{key} is @code{t}.
1043
1044All the other functions described in this chapter that look up keys use
1045@code{lookup-key}.
1046
1047@example
1048@group
1049(lookup-key (current-global-map) "\C-x\C-f")
1050 @result{} find-file
1051@end group
1052@group
1053(lookup-key (current-global-map) "\C-x\C-f12345")
1054 @result{} 2
1055@end group
1056@end example
1057
1058 If @var{key} contains a meta character, that character is implicitly
1059replaced by a two-character sequence: the value of
1060@code{meta-prefix-char}, followed by the corresponding non-meta
1061character. Thus, the first example below is handled by conversion into
1062the second example.
1063
1064@example
1065@group
1066(lookup-key (current-global-map) "\M-f")
1067 @result{} forward-word
1068@end group
1069@group
1070(lookup-key (current-global-map) "\ef")
1071 @result{} forward-word
1072@end group
1073@end example
1074
1075Unlike @code{read-key-sequence}, this function does not modify the
1076specified events in ways that discard information (@pxref{Key Sequence
1077Input}). In particular, it does not convert letters to lower case and
1078it does not change drag events to clicks.
1079@end defun
1080
1081@deffn Command undefined
1082Used in keymaps to undefine keys. It calls @code{ding}, but does
1083not cause an error.
1084@end deffn
1085
1086@defun key-binding key &optional accept-defaults
1087This function returns the binding for @var{key} in the current
1088keymaps, trying all the active keymaps. The result is @code{nil} if
1089@var{key} is undefined in the keymaps.
1090
1091@c Emacs 19 feature
1092The argument @var{accept-defaults} controls checking for default
1093bindings, as in @code{lookup-key}.
1094
1095An error is signaled if @var{key} is not a string or a vector.
1096
1097@example
1098@group
1099(key-binding "\C-x\C-f")
1100 @result{} find-file
1101@end group
1102@end example
1103@end defun
1104
1105@defun local-key-binding key &optional accept-defaults
1106This function returns the binding for @var{key} in the current
1107local keymap, or @code{nil} if it is undefined there.
1108
1109@c Emacs 19 feature
1110The argument @var{accept-defaults} controls checking for default bindings,
1111as in @code{lookup-key} (above).
1112@end defun
1113
1114@defun global-key-binding key &optional accept-defaults
1115This function returns the binding for command @var{key} in the
1116current global keymap, or @code{nil} if it is undefined there.
1117
1118@c Emacs 19 feature
1119The argument @var{accept-defaults} controls checking for default bindings,
1120as in @code{lookup-key} (above).
1121@end defun
1122
1123@c Emacs 19 feature
1124@defun minor-mode-key-binding key &optional accept-defaults
1125This function returns a list of all the active minor mode bindings of
1126@var{key}. More precisely, it returns an alist of pairs
1127@code{(@var{modename} . @var{binding})}, where @var{modename} is the the
1128variable which enables the minor mode, and @var{binding} is @var{key}'s
1129binding in that mode. If @var{key} has no minor-mode bindings, the
1130value is @code{nil}.
1131
1132If the first binding is not a prefix command, all subsequent bindings
1133from other minor modes are omitted, since they would be completely
1134shadowed. Similarly, the list omits non-prefix bindings that follow
1135prefix bindings.
1136
1137The argument @var{accept-defaults} controls checking for default
1138bindings, as in @code{lookup-key} (above).
1139@end defun
1140
1141@defvar meta-prefix-char
1142@cindex @key{ESC}
1143This variable is the meta-prefix character code. It is used when
1144translating a meta character to a two-character sequence so it can be
1145looked up in a keymap. For useful results, the value should be a prefix
1146event (@pxref{Prefix Keys}). The default value is 27, which is the
1147@sc{ASCII} code for @key{ESC}.
1148
1149As long as the value of @code{meta-prefix-char} remains 27, key
1150lookup translates @kbd{M-b} into @kbd{@key{ESC} b}, which is normally
1151defined as the @code{backward-word} command. However, if you set
1152@code{meta-prefix-char} to 24, the code for @kbd{C-x}, then Emacs will
1153translate @kbd{M-b} into @kbd{C-x b}, whose standard binding is the
1154@code{switch-to-buffer} command.
1155
1156@smallexample
1157@group
1158meta-prefix-char ; @r{The default value.}
1159 @result{} 27
1160@end group
1161@group
1162(key-binding "\M-b")
1163 @result{} backward-word
1164@end group
1165@group
1166?\C-x ; @r{The print representation}
1167 @result{} 24 ; @r{of a character.}
1168@end group
1169@group
1170(setq meta-prefix-char 24)
1171 @result{} 24
1172@end group
1173@group
1174(key-binding "\M-b")
1175 @result{} switch-to-buffer ; @r{Now, typing @kbd{M-b} is}
1176 ; @r{like typing @kbd{C-x b}.}
1177
1178(setq meta-prefix-char 27) ; @r{Avoid confusion!}
1179 @result{} 27 ; @r{Restore the default value!}
1180@end group
1181@end smallexample
1182@end defvar
1183
1184@node Changing Key Bindings
1185@section Changing Key Bindings
1186@cindex changing key bindings
1187@cindex rebinding
1188
1189 The way to rebind a key is to change its entry in a keymap. If you
1190change the global keymap, the change is effective in all buffers (except
1191those that override the global binding with a local one). If you change
1192the current buffer's local map, that usually affects all buffers using
1193the same major mode. The @code{global-set-key} and @code{local-set-key}
1194functions are convenient interfaces for these operations. Or you can
1195use @code{define-key} and specify explicitly which map to change.
1196
1197 People often use @code{global-set-key} in their @file{.emacs} file for
1198simple customization. For example,
1199
1200@smallexample
1201(global-set-key "\C-x\C-\\" 'next-line)
1202@end smallexample
1203
1204@noindent
1205or
1206
1207@smallexample
1208(global-set-key [?\C-x ?\C-\\] 'next-line)
1209@end smallexample
1210
1211@noindent
1212redefines @kbd{C-x C-\} to move down a line.
1213
1214@smallexample
1215(global-set-key [M-mouse-1] 'mouse-set-point)
1216@end smallexample
1217
1218@noindent
1219redefines the first (leftmost) mouse button, typed with the Meta key, to
1220set point where you click.
1221
1222@cindex meta character key constants
1223@cindex control character key constants
1224 In writing the key sequence to rebind, it is useful to use the special
1225escape sequences for control and meta characters (@pxref{String Type}).
1226The syntax @samp{\C-} means that the following character is a control
1227character and @samp{\M-} means that the following character is a meta
1228character. Thus, the string @code{"\M-x"} is read as containing a
1229single @kbd{M-x}, @code{"\C-f"} is read as containing a single
1230@kbd{C-f}, and @code{"\M-\C-x"} and @code{"\C-\M-x"} are both read as
1231containing a single @kbd{C-M-x}.
1232
1233 For the functions below, an error is signaled if @var{keymap} is not a
1234keymap or if @var{key} is not a string or vector representing a key
1235sequence. You can use event types (symbols) as shorthand for events
1236that are lists.
1237
1238@defun define-key keymap key binding
1239 This function sets the binding for @var{key} in @var{keymap}. (If
1240@var{key} is more than one event long, the change is actually made
1241in another keymap reached from @var{keymap}.) The argument
1242@var{binding} can be any Lisp object, but only certain types are
1243meaningful. (For a list of meaningful types, see @ref{Key Lookup}.)
1244The value returned by @code{define-key} is @var{binding}.
1245
1246@cindex invalid prefix key error
1247@cindex key sequence error
1248 Every prefix of @var{key} must be a prefix key (i.e., bound to a
1249keymap) or undefined; otherwise an error is signaled.
1250
1251If some prefix of @var{key} is undefined, then @code{define-key} defines
1252it as a prefix key so that the rest of @var{key} may be defined as
1253specified.
1254@end defun
1255
1256 This example creates a sparse keymap and makes a number of bindings:
1257
1258@smallexample
1259@group
1260(setq map (make-sparse-keymap))
1261 @result{} (keymap)
1262@end group
1263@group
1264(define-key map "\C-f" 'forward-char)
1265 @result{} forward-char
1266@end group
1267@group
1268map
1269 @result{} (keymap (6 . forward-char))
1270@end group
1271
1272@group
1273;; @r{Build sparse submap for @kbd{C-x} and bind @kbd{f} in that.}
1274(define-key map "\C-xf" 'forward-word)
1275 @result{} forward-word
1276@end group
1277@group
1278map
1279@result{} (keymap
1280 (24 keymap ; @kbd{C-x}
1281 (102 . forward-word)) ; @kbd{f}
1282 (6 . forward-char)) ; @kbd{C-f}
1283@end group
1284
1285@group
1286;; @r{Bind @kbd{C-p} to the @code{ctl-x-map}.}
1287(define-key map "\C-p" ctl-x-map)
1288;; @code{ctl-x-map}
1289@result{} [nil @dots{} find-file @dots{} backward-kill-sentence]
1290@end group
1291
1292@group
1293;; @r{Bind @kbd{C-f} to @code{foo} in the @code{ctl-x-map}.}
1294(define-key map "\C-p\C-f" 'foo)
1295@result{} 'foo
1296@end group
1297@group
1298map
1299@result{} (keymap ; @r{Note @code{foo} in @code{ctl-x-map}.}
1300 (16 keymap [nil @dots{} foo @dots{} backward-kill-sentence])
1301 (24 keymap
1302 (102 . forward-word))
1303 (6 . forward-char))
1304@end group
1305@end smallexample
1306
1307@noindent
1308Note that storing a new binding for @kbd{C-p C-f} actually works by
1309changing an entry in @code{ctl-x-map}, and this has the effect of
1310changing the bindings of both @kbd{C-p C-f} and @kbd{C-x C-f} in the
1311default global map.
1312
1313@defun substitute-key-definition olddef newdef keymap &optional oldmap
1314@cindex replace bindings
1315This function replaces @var{olddef} with @var{newdef} for any keys in
1316@var{keymap} that were bound to @var{olddef}. In other words,
1317@var{olddef} is replaced with @var{newdef} wherever it appears. The
1318function returns @code{nil}.
1319
1320For example, this redefines @kbd{C-x C-f}, if you do it in an Emacs with
1321standard bindings:
1322
1323@smallexample
1324@group
1325(substitute-key-definition
1326 'find-file 'find-file-read-only (current-global-map))
1327@end group
1328@end smallexample
1329
1330@c Emacs 19 feature
1331If @var{oldmap} is non-@code{nil}, then its bindings determine which
1332keys to rebind. The rebindings still happen in @var{newmap}, not in
1333@var{oldmap}. Thus, you can change one map under the control of the
1334bindings in another. For example,
1335
1336@smallexample
1337(substitute-key-definition
1338 'delete-backward-char 'my-funny-delete
1339 my-map global-map)
1340@end smallexample
1341
1342@noindent
1343puts the special deletion command in @code{my-map} for whichever keys
1344are globally bound to the standard deletion command.
1345
1346@ignore
1347@c Emacs 18 only
1348Prefix keymaps that appear within @var{keymap} are not checked
1349recursively for keys bound to @var{olddef}; they are not changed at all.
1350Perhaps it would be better to check nested keymaps recursively.
1351@end ignore
1352
1353Here is an example showing a keymap before and after substitution:
1354
1355@smallexample
1356@group
1357(setq map '(keymap
1358 (?1 . olddef-1)
1359 (?2 . olddef-2)
1360 (?3 . olddef-1)))
1361@result{} (keymap (49 . olddef-1) (50 . olddef-2) (51 . olddef-1))
1362@end group
1363
1364@group
1365(substitute-key-definition 'olddef-1 'newdef map)
1366@result{} nil
1367@end group
1368@group
1369map
1370@result{} (keymap (49 . newdef) (50 . olddef-2) (51 . newdef))
1371@end group
1372@end smallexample
1373@end defun
1374
1375@defun suppress-keymap keymap &optional nodigits
1376@cindex @code{self-insert-command} override
1377This function changes the contents of the full keymap @var{keymap} by
1378making all the printing characters undefined. More precisely, it binds
1379them to the command @code{undefined}. This makes ordinary insertion of
1380text impossible. @code{suppress-keymap} returns @code{nil}.
1381
1382If @var{nodigits} is @code{nil}, then @code{suppress-keymap} defines
1383digits to run @code{digit-argument}, and @kbd{-} to run
1384@code{negative-argument}. Otherwise it makes them undefined like the
1385rest of the printing characters.
1386
1387@cindex yank suppression
1388@cindex @code{quoted-insert} suppression
1389The @code{suppress-keymap} function does not make it impossible to
1390modify a buffer, as it does not suppress commands such as @code{yank}
1391and @code{quoted-insert}. To prevent any modification of a buffer, make
1392it read-only (@pxref{Read Only Buffers}).
1393
1394Since this function modifies @var{keymap}, you would normally use it
1395on a newly created keymap. Operating on an existing keymap
1396that is used for some other purpose is likely to cause trouble; for
1397example, suppressing @code{global-map} would make it impossible to use
1398most of Emacs.
1399
1400Most often, @code{suppress-keymap} is used to initialize local
1401keymaps of modes such as Rmail and Dired where insertion of text is not
1402desirable and the buffer is read-only. Here is an example taken from
1403the file @file{emacs/lisp/dired.el}, showing how the local keymap for
1404Dired mode is set up:
1405
1406@smallexample
1407@group
1408 @dots{}
1409 (setq dired-mode-map (make-keymap))
1410 (suppress-keymap dired-mode-map)
1411 (define-key dired-mode-map "r" 'dired-rename-file)
1412 (define-key dired-mode-map "\C-d" 'dired-flag-file-deleted)
1413 (define-key dired-mode-map "d" 'dired-flag-file-deleted)
1414 (define-key dired-mode-map "v" 'dired-view-file)
1415 (define-key dired-mode-map "e" 'dired-find-file)
1416 (define-key dired-mode-map "f" 'dired-find-file)
1417 @dots{}
1418@end group
1419@end smallexample
1420@end defun
1421
1422@node Key Binding Commands
1423@section Commands for Binding Keys
1424
1425 This section describes some convenient interactive interfaces for
1426changing key bindings. They work by calling @code{define-key}.
1427
1428@deffn Command global-set-key key definition
1429 This function sets the binding of @var{key} in the current global map
1430to @var{definition}.
1431
1432@smallexample
1433@group
1434(global-set-key @var{key} @var{definition})
1435@equiv{}
1436(define-key (current-global-map) @var{key} @var{definition})
1437@end group
1438@end smallexample
1439@end deffn
1440
1441@deffn Command global-unset-key key
1442@cindex unbinding keys
1443 This function removes the binding of @var{key} from the current
1444global map.
1445
1446One use of this function is in preparation for defining a longer key
1447which uses it implicitly as a prefix---which would not be allowed if
1448@var{key} has a non-prefix binding. For example:
1449
1450@smallexample
1451@group
1452(global-unset-key "\C-l")
1453 @result{} nil
1454@end group
1455@group
1456(global-set-key "\C-l\C-l" 'redraw-display)
1457 @result{} nil
1458@end group
1459@end smallexample
1460
1461This function is implemented simply using @code{define-key}:
1462
1463@smallexample
1464@group
1465(global-unset-key @var{key})
1466@equiv{}
1467(define-key (current-global-map) @var{key} nil)
1468@end group
1469@end smallexample
1470@end deffn
1471
1472@deffn Command local-set-key key definition
1473 This function sets the binding of @var{key} in the current local
1474keymap to @var{definition}.
1475
1476@smallexample
1477@group
1478(local-set-key @var{key} @var{definition})
1479@equiv{}
1480(define-key (current-local-map) @var{key} @var{definition})
1481@end group
1482@end smallexample
1483@end deffn
1484
1485@deffn Command local-unset-key key
1486 This function removes the binding of @var{key} from the current
1487local map.
1488
1489@smallexample
1490@group
1491(local-unset-key @var{key})
1492@equiv{}
1493(define-key (current-local-map) @var{key} nil)
1494@end group
1495@end smallexample
1496@end deffn
1497
1498@node Scanning Keymaps
1499@section Scanning Keymaps
1500
1501 This section describes functions used to scan all the current keymaps
1502for the sake of printing help information.
1503
1504@defun accessible-keymaps keymap &optional prefix
1505This function returns a list of all the keymaps that can be accessed
1506(via prefix keys) from @var{keymap}. The value is an association list
1507with elements of the form @code{(@var{key} .@: @var{map})}, where
1508@var{key} is a prefix key whose definition in @var{keymap} is
1509@var{map}.
1510
1511The elements of the alist are ordered so that the @var{key} increases
1512in length. The first element is always @code{("" .@: @var{keymap})},
1513because the specified keymap is accessible from itself with a prefix of
1514no events.
1515
1516If @var{prefix} is given, it should be a prefix key sequence; then
1517@code{accessible-keymaps} includes only the submaps whose prefixes start
1518with @var{prefix}. These elements look just as they do in the value of
1519@code{(accessible-keymaps)}; the only difference is that some elements
1520are omitted.
1521
1522In the example below, the returned alist indicates that the key
1523@key{ESC}, which is displayed as @samp{^[}, is a prefix key whose
1524definition is the sparse keymap @code{(keymap (83 .@: center-paragraph)
1525(115 .@: foo))}.
1526
1527@smallexample
1528@group
1529(accessible-keymaps (current-local-map))
1530@result{}(("" keymap
1531 (27 keymap ; @r{Note this keymap for @key{ESC} is repeated below.}
1532 (83 . center-paragraph)
1533 (115 . center-line))
1534 (9 . tab-to-tab-stop))
1535@end group
1536
1537@group
1538 ("^[" keymap
1539 (83 . center-paragraph)
1540 (115 . foo)))
1541@end group
1542@end smallexample
1543
1544In the following example, @kbd{C-h} is a prefix key that uses a sparse
1545keymap starting with @code{(keymap (118 . describe-variable)@dots{})}.
1546Another prefix, @kbd{C-x 4}, uses a keymap which happens to be
1547@code{ctl-x-4-map}. The event @code{mode-line} is one of several dummy
1548events used as prefixes for mouse actions in special parts of a window.
1549
1550@smallexample
1551@group
1552(accessible-keymaps (current-global-map))
1553@result{} (("" keymap [set-mark-command beginning-of-line @dots{}
1554 delete-backward-char])
1555@end group
1556@group
1557 ("^H" keymap (118 . describe-variable) @dots{}
1558 (8 . help-for-help))
1559@end group
1560@group
1561 ("^X" keymap [x-flush-mouse-queue @dots{}
1562 backward-kill-sentence])
1563@end group
1564@group
1565 ("^[" keymap [mark-sexp backward-sexp @dots{}
1566 backward-kill-word])
1567@end group
1568 ("^X4" keymap (15 . display-buffer) @dots{})
1569@group
1570 ([mode-line] keymap
1571 (S-mouse-2 . mouse-split-window-horizontally) @dots{}))
1572@end group
1573@end smallexample
1574
1575@noindent
1576These are not all the keymaps you would see in an actual case.
1577@end defun
1578
1579@defun where-is-internal command &optional keymap firstonly noindirect
1580This function returns a list of key sequences (of any length) that are
1581bound to @var{command} in a set of keymaps.
1582
1583The argument @var{command} can be any object; it is compared with all
1584keymap entries using @code{eq}.
1585
1586If @var{keymap} is @code{nil}, then the maps used are the current active
1587keymaps, disregarding @code{overriding-local-map} (that is, pretending
1588its value is @code{nil}). If @var{keymap} is non-@code{nil}, then the
1589maps searched are @var{keymap} and the global keymap.
1590
1591Usually it's best to use @code{overriding-local-map} as the expression
1592for @var{keymap}. Then @code{where-is-internal} searches precisely the
1593keymaps that are active. To search only the global map, pass
1594@code{(keymap)} (an empty keymap) as @var{keymap}.
1595
1596If @var{firstonly} is @code{non-ascii}, then the value is a single
1597string representing the first key sequence found, rather than a list of
1598all possible key sequences. If @var{firstonly} is @code{t}, then the
1599value is the first key sequence, except that key sequences consisting
1600entirely of @sc{ASCII} characters (or meta variants of @sc{ASCII}
1601characters) are preferred to all other key sequences.
1602
1603If @var{noindirect} is non-@code{nil}, @code{where-is-internal} doesn't
1604follow indirections to other keymaps or slots. This makes it possible
1605to search for an indirect definition itself.
1606
1607This function is used by @code{where-is} (@pxref{Help, , Help, emacs,
1608The GNU Emacs Manual}).
1609
1610@smallexample
1611@group
1612(where-is-internal 'describe-function)
1613 @result{} ("\^hf" "\^hd")
1614@end group
1615@end smallexample
1616@end defun
1617
1618@deffn Command describe-bindings prefix
1619This function creates a listing of all defined keys, and their
1620definitions. It writes the listing in a buffer named @samp{*Help*} and
1621displays it in a window.
1622
1623The listing describes meta characters as @key{ESC} followed by the
1624corresponding non-meta character.
1625
1626When several characters with consecutive @sc{ASCII} codes have the
1627same definition, they are shown together, as
1628@samp{@var{firstchar}..@var{lastchar}}. In this instance, you need to
1629know the @sc{ASCII} codes to understand which characters this means.
1630For example, in the default global map, the characters @samp{@key{SPC}
1631..@: ~} are described by a single line. @key{SPC} is @sc{ASCII} 32,
1632@kbd{~} is @sc{ASCII} 126, and the characters between them include all
1633the normal printing characters, (e.g., letters, digits, punctuation,
1634etc.@:); all these characters are bound to @code{self-insert-command}.
1635
1636If @var{prefix} is non-@code{nil}, it should be a prefix key; then the
1637listing includes only keys that start with @var{prefix}.
1638@end deffn
diff --git a/lispref/lists.texi b/lispref/lists.texi
new file mode 100644
index 00000000000..8253063d2ce
--- /dev/null
+++ b/lispref/lists.texi
@@ -0,0 +1,1384 @@
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/lists
6@node Lists, Sequences Arrays Vectors, Strings and Characters, Top
7@chapter Lists
8@cindex list
9@cindex element (of list)
10
11 A @dfn{list} represents a sequence of zero or more elements (which may
12be any Lisp objects). The important difference between lists and
13vectors is that two or more lists can share part of their structure; in
14addition, you can insert or delete elements in a list without copying
15the whole list.
16
17@menu
18* Cons Cells:: How lists are made out of cons cells.
19* Lists as Boxes:: Graphical notation to explain lists.
20* List-related Predicates:: Is this object a list? Comparing two lists.
21* List Elements:: Extracting the pieces of a list.
22* Building Lists:: Creating list structure.
23* Modifying Lists:: Storing new pieces into an existing list.
24* Sets And Lists:: A list can represent a finite mathematical set.
25* Association Lists:: A list can represent a finite relation or mapping.
26@end menu
27
28@node Cons Cells
29@section Lists and Cons Cells
30@cindex lists and cons cells
31@cindex @code{nil} and lists
32
33 Lists in Lisp are not a primitive data type; they are built up from
34@dfn{cons cells}. A cons cell is a data object which represents an ordered
35pair. It records two Lisp objects, one labeled as the @sc{car}, and the
36other labeled as the @sc{cdr}. These names are traditional; @sc{cdr} is
37pronounced ``could-er.''
38
39 A list is a series of cons cells chained together, one cons cell per
40element of the list. By convention, the @sc{car}s of the cons cells are
41the elements of the list, and the @sc{cdr}s are used to chain the list:
42the @sc{cdr} of each cons cell is the following cons cell. The @sc{cdr}
43of the last cons cell is @code{nil}. This asymmetry between the
44@sc{car} and the @sc{cdr} is entirely a matter of convention; at the
45level of cons cells, the @sc{car} and @sc{cdr} slots have the same
46characteristics.
47
48 The symbol @code{nil} is considered a list as well as a symbol; it is
49the list with no elements. For convenience, the symbol @code{nil} is
50considered to have @code{nil} as its @sc{cdr} (and also as its
51@sc{car}).
52
53 The @sc{cdr} of any nonempty list @var{l} is a list containing all the
54elements of @var{l} except the first.
55
56@node Lists as Boxes
57@comment node-name, next, previous, up
58@section Lists as Linked Pairs of Boxes
59@cindex box representation for lists
60@cindex lists represented as boxes
61@cindex cons cell as box
62
63 A cons cell can be illustrated as a pair of boxes. The first box
64represents the @sc{car} and the second box represents the @sc{cdr}.
65Here is an illustration of the two-element list, @code{(tulip lily)},
66made from two cons cells:
67
68@example
69@group
70 --------------- ---------------
71| car | cdr | | car | cdr |
72| tulip | o---------->| lily | nil |
73| | | | | |
74 --------------- ---------------
75@end group
76@end example
77
78 Each pair of boxes represents a cons cell. Each box ``refers to'',
79``points to'' or ``contains'' a Lisp object. (These terms are
80synonymous.) The first box, which is the @sc{car} of the first cons
81cell, contains the symbol @code{tulip}. The arrow from the @sc{cdr} of
82the first cons cell to the second cons cell indicates that the @sc{cdr}
83of the first cons cell points to the second cons cell.
84
85 The same list can be illustrated in a different sort of box notation
86like this:
87
88@example
89@group
90 ___ ___ ___ ___
91 |___|___|--> |___|___|--> nil
92 | |
93 | |
94 --> tulip --> lily
95@end group
96@end example
97
98 Here is a more complex illustration, showing the three-element list,
99@code{((pine needles) oak maple)}, the first element of which is a
100two-element list:
101
102@example
103@group
104 ___ ___ ___ ___ ___ ___
105 |___|___|--> |___|___|--> |___|___|--> nil
106 | | |
107 | | |
108 | --> oak --> maple
109 |
110 | ___ ___ ___ ___
111 --> |___|___|--> |___|___|--> nil
112 | |
113 | |
114 --> pine --> needles
115@end group
116@end example
117
118 The same list represented in the first box notation looks like this:
119
120@example
121@group
122 -------------- -------------- --------------
123| car | cdr | | car | cdr | | car | cdr |
124| o | o------->| oak | o------->| maple | nil |
125| | | | | | | | | |
126 -- | --------- -------------- --------------
127 |
128 |
129 | -------------- ----------------
130 | | car | cdr | | car | cdr |
131 ------>| pine | o------->| needles | nil |
132 | | | | | |
133 -------------- ----------------
134@end group
135@end example
136
137 @xref{List Type}, for the read and print syntax of lists, and for more
138``box and arrow'' illustrations of lists.
139
140@node List-related Predicates
141@section Predicates on Lists
142
143 The following predicates test whether a Lisp object is an atom, is a
144cons cell or is a list, or whether it is the distinguished object
145@code{nil}. (Many of these predicates can be defined in terms of the
146others, but they are used so often that it is worth having all of them.)
147
148@defun consp object
149This function returns @code{t} if @var{object} is a cons cell, @code{nil}
150otherwise. @code{nil} is not a cons cell, although it @emph{is} a list.
151@end defun
152
153@defun atom object
154@cindex atoms
155This function returns @code{t} if @var{object} is an atom, @code{nil}
156otherwise. All objects except cons cells are atoms. The symbol
157@code{nil} is an atom and is also a list; it is the only Lisp object
158which is both.
159
160@example
161(atom @var{object}) @equiv{} (not (consp @var{object}))
162@end example
163@end defun
164
165@defun listp object
166This function returns @code{t} if @var{object} is a cons cell or
167@code{nil}. Otherwise, it returns @code{nil}.
168
169@example
170@group
171(listp '(1))
172 @result{} t
173@end group
174@group
175(listp '())
176 @result{} t
177@end group
178@end example
179@end defun
180
181@defun nlistp object
182This function is the opposite of @code{listp}: it returns @code{t} if
183@var{object} is not a list. Otherwise, it returns @code{nil}.
184
185@example
186(listp @var{object}) @equiv{} (not (nlistp @var{object}))
187@end example
188@end defun
189
190@defun null object
191This function returns @code{t} if @var{object} is @code{nil}, and
192returns @code{nil} otherwise. This function is identical to @code{not},
193but as a matter of clarity we use @code{null} when @var{object} is
194considered a list and @code{not} when it is considered a truth value
195(see @code{not} in @ref{Combining Conditions}).
196
197@example
198@group
199(null '(1))
200 @result{} nil
201@end group
202@group
203(null '())
204 @result{} t
205@end group
206@end example
207@end defun
208
209@need 1000
210
211@node List Elements
212@section Accessing Elements of Lists
213@cindex list elements
214
215@defun car cons-cell
216This function returns the value pointed to by the first pointer of the
217cons cell @var{cons-cell}. Expressed another way, this function
218returns the @sc{car} of @var{cons-cell}.
219
220As a special case, if @var{cons-cell} is @code{nil}, then @code{car}
221is defined to return @code{nil}; therefore, any list is a valid argument
222for @code{car}. An error is signaled if the argument is not a cons cell
223or @code{nil}.
224
225@example
226@group
227(car '(a b c))
228 @result{} a
229@end group
230@group
231(car '())
232 @result{} nil
233@end group
234@end example
235@end defun
236
237@defun cdr cons-cell
238This function returns the value pointed to by the second pointer of
239the cons cell @var{cons-cell}. Expressed another way, this function
240returns the @sc{cdr} of @var{cons-cell}.
241
242As a special case, if @var{cons-cell} is @code{nil}, then @code{cdr}
243is defined to return @code{nil}; therefore, any list is a valid argument
244for @code{cdr}. An error is signaled if the argument is not a cons cell
245or @code{nil}.
246
247@example
248@group
249(cdr '(a b c))
250 @result{} (b c)
251@end group
252@group
253(cdr '())
254 @result{} nil
255@end group
256@end example
257@end defun
258
259@defun car-safe object
260This function lets you take the @sc{car} of a cons cell while avoiding
261errors for other data types. It returns the @sc{car} of @var{object} if
262@var{object} is a cons cell, @code{nil} otherwise. This is in contrast
263to @code{car}, which signals an error if @var{object} is not a list.
264
265@example
266@group
267(car-safe @var{object})
268@equiv{}
269(let ((x @var{object}))
270 (if (consp x)
271 (car x)
272 nil))
273@end group
274@end example
275@end defun
276
277@defun cdr-safe object
278This function lets you take the @sc{cdr} of a cons cell while
279avoiding errors for other data types. It returns the @sc{cdr} of
280@var{object} if @var{object} is a cons cell, @code{nil} otherwise.
281This is in contrast to @code{cdr}, which signals an error if
282@var{object} is not a list.
283
284@example
285@group
286(cdr-safe @var{object})
287@equiv{}
288(let ((x @var{object}))
289 (if (consp x)
290 (cdr x)
291 nil))
292@end group
293@end example
294@end defun
295
296@defun nth n list
297This function returns the @var{n}th element of @var{list}. Elements
298are numbered starting with zero, so the @sc{car} of @var{list} is
299element number zero. If the length of @var{list} is @var{n} or less,
300the value is @code{nil}.
301
302If @var{n} is negative, @code{nth} returns the first element of
303@var{list}.
304
305@example
306@group
307(nth 2 '(1 2 3 4))
308 @result{} 3
309@end group
310@group
311(nth 10 '(1 2 3 4))
312 @result{} nil
313@end group
314@group
315(nth -3 '(1 2 3 4))
316 @result{} 1
317
318(nth n x) @equiv{} (car (nthcdr n x))
319@end group
320@end example
321@end defun
322
323@defun nthcdr n list
324This function returns the @var{n}th @sc{cdr} of @var{list}. In other
325words, it removes the first @var{n} links of @var{list} and returns
326what follows.
327
328If @var{n} is zero or negative, @code{nthcdr} returns all of
329@var{list}. If the length of @var{list} is @var{n} or less,
330@code{nthcdr} returns @code{nil}.
331
332@example
333@group
334(nthcdr 1 '(1 2 3 4))
335 @result{} (2 3 4)
336@end group
337@group
338(nthcdr 10 '(1 2 3 4))
339 @result{} nil
340@end group
341@group
342(nthcdr -3 '(1 2 3 4))
343 @result{} (1 2 3 4)
344@end group
345@end example
346@end defun
347
348@node Building Lists
349@comment node-name, next, previous, up
350@section Building Cons Cells and Lists
351@cindex cons cells
352@cindex building lists
353
354 Many functions build lists, as lists reside at the very heart of Lisp.
355@code{cons} is the fundamental list-building function; however, it is
356interesting to note that @code{list} is used more times in the source
357code for Emacs than @code{cons}.
358
359@defun cons object1 object2
360This function is the fundamental function used to build new list
361structure. It creates a new cons cell, making @var{object1} the
362@sc{car}, and @var{object2} the @sc{cdr}. It then returns the new cons
363cell. The arguments @var{object1} and @var{object2} may be any Lisp
364objects, but most often @var{object2} is a list.
365
366@example
367@group
368(cons 1 '(2))
369 @result{} (1 2)
370@end group
371@group
372(cons 1 '())
373 @result{} (1)
374@end group
375@group
376(cons 1 2)
377 @result{} (1 . 2)
378@end group
379@end example
380
381@cindex consing
382@code{cons} is often used to add a single element to the front of a
383list. This is called @dfn{consing the element onto the list}. For
384example:
385
386@example
387(setq list (cons newelt list))
388@end example
389
390Note that there is no conflict between the variable named @code{list}
391used in this example and the function named @code{list} described below;
392any symbol can serve both purposes.
393@end defun
394
395@defun list &rest objects
396This function creates a list with @var{objects} as its elements. The
397resulting list is always @code{nil}-terminated. If no @var{objects}
398are given, the empty list is returned.
399
400@example
401@group
402(list 1 2 3 4 5)
403 @result{} (1 2 3 4 5)
404@end group
405@group
406(list 1 2 '(3 4 5) 'foo)
407 @result{} (1 2 (3 4 5) foo)
408@end group
409@group
410(list)
411 @result{} nil
412@end group
413@end example
414@end defun
415
416@defun make-list length object
417This function creates a list of length @var{length}, in which all the
418elements have the identical value @var{object}. Compare
419@code{make-list} with @code{make-string} (@pxref{Creating Strings}).
420
421@example
422@group
423(make-list 3 'pigs)
424 @result{} (pigs pigs pigs)
425@end group
426@group
427(make-list 0 'pigs)
428 @result{} nil
429@end group
430@end example
431@end defun
432
433@defun append &rest sequences
434@cindex copying lists
435This function returns a list containing all the elements of
436@var{sequences}. The @var{sequences} may be lists, vectors, or strings.
437All arguments except the last one are copied, so none of them are
438altered.
439
440 The final argument to @code{append} may be any object but it is
441typically a list. The final argument is not copied or converted; it
442becomes part of the structure of the new list.
443
444 Here is an example:
445
446@example
447@group
448(setq trees '(pine oak))
449 @result{} (pine oak)
450(setq more-trees (append '(maple birch) trees))
451 @result{} (maple birch pine oak)
452@end group
453
454@group
455trees
456 @result{} (pine oak)
457more-trees
458 @result{} (maple birch pine oak)
459@end group
460@group
461(eq trees (cdr (cdr more-trees)))
462 @result{} t
463@end group
464@end example
465
466You can see what happens by looking at a box diagram. The variable
467@code{trees} is set to the list @code{(pine oak)} and then the variable
468@code{more-trees} is set to the list @code{(maple birch pine oak)}.
469However, the variable @code{trees} continues to refer to the original
470list:
471
472@smallexample
473@group
474more-trees trees
475| |
476| ___ ___ ___ ___ -> ___ ___ ___ ___
477 --> |___|___|--> |___|___|--> |___|___|--> |___|___|--> nil
478 | | | |
479 | | | |
480 --> maple -->birch --> pine --> oak
481@end group
482@end smallexample
483
484An empty sequence contributes nothing to the value returned by
485@code{append}. As a consequence of this, a final @code{nil} argument
486forces a copy of the previous argument.
487
488@example
489@group
490trees
491 @result{} (pine oak)
492@end group
493@group
494(setq wood (append trees ()))
495 @result{} (pine oak)
496@end group
497@group
498wood
499 @result{} (pine oak)
500@end group
501@group
502(eq wood trees)
503 @result{} nil
504@end group
505@end example
506
507@noindent
508This once was the usual way to copy a list, before the function
509@code{copy-sequence} was invented. @xref{Sequences Arrays Vectors}.
510
511With the help of @code{apply}, we can append all the lists in a list of
512lists:
513
514@example
515@group
516(apply 'append '((a b c) nil (x y z) nil))
517 @result{} (a b c x y z)
518@end group
519@end example
520
521If no @var{sequences} are given, @code{nil} is returned:
522
523@example
524@group
525(append)
526 @result{} nil
527@end group
528@end example
529
530See @code{nconc} in @ref{Rearrangement}, for a way to join lists with no
531copying.
532
533Integers are also allowed as arguments to @code{append}. They are
534converted to strings of digits making up the decimal print
535representation of the integer, and these strings are then appended.
536Here's what happens:
537
538@example
539@group
540(setq trees '(pine oak))
541 @result{} (pine oak)
542@end group
543@group
544(char-to-string 54)
545 @result{} "6"
546@end group
547@group
548(setq longer-list (append trees 6 '(spruce)))
549 @result{} (pine oak 54 spruce)
550@end group
551@group
552(setq x-list (append trees 6 6))
553 @result{} (pine oak 54 . 6)
554@end group
555@end example
556
557This special case exists for compatibility with Mocklisp, and we don't
558recommend you take advantage of it. If you want to convert an integer
559in this way, use @code{format} (@pxref{Formatting Strings}) or
560@code{number-to-string} (@pxref{String Conversion}).
561@end defun
562
563@defun reverse list
564This function creates a new list whose elements are the elements of
565@var{list}, but in reverse order. The original argument @var{list} is
566@emph{not} altered.
567
568@example
569@group
570(setq x '(1 2 3 4))
571 @result{} (1 2 3 4)
572@end group
573@group
574(reverse x)
575 @result{} (4 3 2 1)
576x
577 @result{} (1 2 3 4)
578@end group
579@end example
580@end defun
581
582@node Modifying Lists
583@section Modifying Existing List Structure
584
585 You can modify the @sc{car} and @sc{cdr} contents of a cons cell with the
586primitives @code{setcar} and @code{setcdr}.
587
588@cindex CL note---@code{rplaca} vrs @code{setcar}
589@quotation
590@findex rplaca
591@findex rplacd
592@b{Common Lisp note:} Common Lisp uses functions @code{rplaca} and
593@code{rplacd} to alter list structure; they change structure the same
594way as @code{setcar} and @code{setcdr}, but the Common Lisp functions
595return the cons cell while @code{setcar} and @code{setcdr} return the
596new @sc{car} or @sc{cdr}.
597@end quotation
598
599@menu
600* Setcar:: Replacing an element in a list.
601* Setcdr:: Replacing part of the list backbone.
602 This can be used to remove or add elements.
603* Rearrangement:: Reordering the elements in a list; combining lists.
604@end menu
605
606@node Setcar
607@subsection Altering List Elements with @code{setcar}
608
609 Changing the @sc{car} of a cons cell is done with @code{setcar}, which
610replaces one element of a list with a different element.
611
612@defun setcar cons object
613This function stores @var{object} as the new @sc{car} of @var{cons},
614replacing its previous @sc{car}. It returns the value @var{object}.
615For example:
616
617@example
618@group
619(setq x '(1 2))
620 @result{} (1 2)
621@end group
622@group
623(setcar x 4)
624 @result{} 4
625@end group
626@group
627x
628 @result{} (4 2)
629@end group
630@end example
631@end defun
632
633 When a cons cell is part of the shared structure of several lists,
634storing a new @sc{car} into the cons changes one element of each of
635these lists. Here is an example:
636
637@example
638@group
639;; @r{Create two lists that are partly shared.}
640(setq x1 '(a b c))
641 @result{} (a b c)
642(setq x2 (cons 'z (cdr x1)))
643 @result{} (z b c)
644@end group
645
646@group
647;; @r{Replace the @sc{car} of a shared link.}
648(setcar (cdr x1) 'foo)
649 @result{} foo
650x1 ; @r{Both lists are changed.}
651 @result{} (a foo c)
652x2
653 @result{} (z foo c)
654@end group
655
656@group
657;; @r{Replace the @sc{car} of a link that is not shared.}
658(setcar x1 'baz)
659 @result{} baz
660x1 ; @r{Only one list is changed.}
661 @result{} (baz foo c)
662x2
663 @result{} (z foo c)
664@end group
665@end example
666
667 Here is a graphical depiction of the shared structure of the two lists
668in the variables @code{x1} and @code{x2}, showing why replacing @code{b}
669changes them both:
670
671@example
672@group
673 ___ ___ ___ ___ ___ ___
674x1---> |___|___|----> |___|___|--> |___|___|--> nil
675 | --> | |
676 | | | |
677 --> a | --> b --> c
678 |
679 ___ ___ |
680x2--> |___|___|--
681 |
682 |
683 --> z
684@end group
685@end example
686
687 Here is an alternative form of box diagram, showing the same relationship:
688
689@example
690@group
691x1:
692 -------------- -------------- --------------
693| car | cdr | | car | cdr | | car | cdr |
694| a | o------->| b | o------->| c | nil |
695| | | -->| | | | | |
696 -------------- | -------------- --------------
697 |
698x2: |
699 -------------- |
700| car | cdr | |
701| z | o----
702| | |
703 --------------
704@end group
705@end example
706
707@node Setcdr
708@subsection Altering the CDR of a List
709
710 The lowest-level primitive for modifying a @sc{cdr} is @code{setcdr}:
711
712@defun setcdr cons object
713This function stores @var{object} into the @sc{cdr} of @var{cons}. The
714value returned is @var{object}, not @var{cons}.
715@end defun
716
717 Here is an example of replacing the @sc{cdr} of a list with a
718different list. All but the first element of the list are removed in
719favor of a different sequence of elements. The first element is
720unchanged, because it resides in the @sc{car} of the list, and is not
721reached via the @sc{cdr}.
722
723@example
724@group
725(setq x '(1 2 3))
726 @result{} (1 2 3)
727@end group
728@group
729(setcdr x '(4))
730 @result{} (4)
731@end group
732@group
733x
734 @result{} (1 4)
735@end group
736@end example
737
738 You can delete elements from the middle of a list by altering the
739@sc{cdr}s of the cons cells in the list. For example, here we delete
740the second element, @code{b}, from the list @code{(a b c)}, by changing
741the @sc{cdr} of the first cell:
742
743@example
744@group
745(setq x1 '(a b c))
746 @result{} (a b c)
747(setcdr x1 (cdr (cdr x1)))
748 @result{} (c)
749x1
750 @result{} (a c)
751@end group
752@end example
753
754 Here is the result in box notation:
755
756@example
757@group
758 --------------------
759 | |
760 -------------- | -------------- | --------------
761| car | cdr | | | car | cdr | -->| car | cdr |
762| a | o----- | b | o-------->| c | nil |
763| | | | | | | | |
764 -------------- -------------- --------------
765@end group
766@end example
767
768@noindent
769The second cons cell, which previously held the element @code{b}, still
770exists and its @sc{car} is still @code{b}, but it no longer forms part
771of this list.
772
773 It is equally easy to insert a new element by changing @sc{cdr}s:
774
775@example
776@group
777(setq x1 '(a b c))
778 @result{} (a b c)
779(setcdr x1 (cons 'd (cdr x1)))
780 @result{} (d b c)
781x1
782 @result{} (a d b c)
783@end group
784@end example
785
786 Here is this result in box notation:
787
788@smallexample
789@group
790 -------------- ------------- -------------
791| car | cdr | | car | cdr | | car | cdr |
792| a | o | -->| b | o------->| c | nil |
793| | | | | | | | | | |
794 --------- | -- | ------------- -------------
795 | |
796 ----- --------
797 | |
798 | --------------- |
799 | | car | cdr | |
800 -->| d | o------
801 | | |
802 ---------------
803@end group
804@end smallexample
805
806@node Rearrangement
807@subsection Functions that Rearrange Lists
808@cindex rearrangement of lists
809@cindex modification of lists
810
811 Here are some functions that rearrange lists ``destructively'' by
812modifying the @sc{cdr}s of their component cons cells. We call these
813functions ``destructive'' because they chew up the original lists passed
814to them as arguments, to produce a new list that is the returned value.
815
816@defun nconc &rest lists
817@cindex concatenating lists
818@cindex joining lists
819This function returns a list containing all the elements of @var{lists}.
820Unlike @code{append} (@pxref{Building Lists}), the @var{lists} are
821@emph{not} copied. Instead, the last @sc{cdr} of each of the
822@var{lists} is changed to refer to the following list. The last of the
823@var{lists} is not altered. For example:
824
825@example
826@group
827(setq x '(1 2 3))
828 @result{} (1 2 3)
829@end group
830@group
831(nconc x '(4 5))
832 @result{} (1 2 3 4 5)
833@end group
834@group
835x
836 @result{} (1 2 3 4 5)
837@end group
838@end example
839
840 Since the last argument of @code{nconc} is not itself modified, it is
841reasonable to use a constant list, such as @code{'(4 5)}, as in the
842above example. For the same reason, the last argument need not be a
843list:
844
845@example
846@group
847(setq x '(1 2 3))
848 @result{} (1 2 3)
849@end group
850@group
851(nconc x 'z)
852 @result{} (1 2 3 . z)
853@end group
854@group
855x
856 @result{} (1 2 3 . z)
857@end group
858@end example
859
860A common pitfall is to use a quoted constant list as a non-last
861argument to @code{nconc}. If you do this, your program will change
862each time you run it! Here is what happens:
863
864@smallexample
865@group
866(defun add-foo (x) ; @r{We want this function to add}
867 (nconc '(foo) x)) ; @r{@code{foo} to the front of its arg.}
868@end group
869
870@group
871(symbol-function 'add-foo)
872 @result{} (lambda (x) (nconc (quote (foo)) x))
873@end group
874
875@group
876(setq xx (add-foo '(1 2))) ; @r{It seems to work.}
877 @result{} (foo 1 2)
878@end group
879@group
880(setq xy (add-foo '(3 4))) ; @r{What happened?}
881 @result{} (foo 1 2 3 4)
882@end group
883@group
884(eq xx xy)
885 @result{} t
886@end group
887
888@group
889(symbol-function 'add-foo)
890 @result{} (lambda (x) (nconc (quote (foo 1 2 3 4) x)))
891@end group
892@end smallexample
893@end defun
894
895@defun nreverse list
896@cindex reversing a list
897 This function reverses the order of the elements of @var{list}.
898Unlike @code{reverse}, @code{nreverse} alters its argument destructively
899by reversing the @sc{cdr}s in the cons cells forming the list. The cons
900cell which used to be the last one in @var{list} becomes the first cell
901of the value.
902
903 For example:
904
905@example
906@group
907(setq x '(1 2 3 4))
908 @result{} (1 2 3 4)
909@end group
910@group
911x
912 @result{} (1 2 3 4)
913(nreverse x)
914 @result{} (4 3 2 1)
915@end group
916@group
917;; @r{The cell that was first is now last.}
918x
919 @result{} (1)
920@end group
921@end example
922
923 To avoid confusion, we usually store the result of @code{nreverse}
924back in the same variable which held the original list:
925
926@example
927(setq x (nreverse x))
928@end example
929
930 Here is the @code{nreverse} of our favorite example, @code{(a b c)},
931presented graphically:
932
933@smallexample
934@group
935@r{Original list head:} @r{Reversed list:}
936 ------------- ------------- ------------
937| car | cdr | | car | cdr | | car | cdr |
938| a | nil |<-- | b | o |<-- | c | o |
939| | | | | | | | | | | | |
940 ------------- | --------- | - | -------- | -
941 | | | |
942 ------------- ------------
943@end group
944@end smallexample
945@end defun
946
947@defun sort list predicate
948@cindex stable sort
949@cindex sorting lists
950This function sorts @var{list} stably, though destructively, and
951returns the sorted list. It compares elements using @var{predicate}. A
952stable sort is one in which elements with equal sort keys maintain their
953relative order before and after the sort. Stability is important when
954successive sorts are used to order elements according to different
955criteria.
956
957The argument @var{predicate} must be a function that accepts two
958arguments. It is called with two elements of @var{list}. To get an
959increasing order sort, the @var{predicate} should return @code{t} if the
960first element is ``less than'' the second, or @code{nil} if not.
961
962The destructive aspect of @code{sort} is that it rearranges the cons
963cells forming @var{list} by changing @sc{cdr}s. A nondestructive sort
964function would create new cons cells to store the elements in their
965sorted order. If you wish to make a sorted copy without destroying the
966original, copy it first with @code{copy-sequence} and then sort.
967
968Sorting does not change the @sc{car}s of the cons cells in @var{list};
969the cons cell that originally contained the element @code{a} in
970@var{list} still has @code{a} in its @sc{car} after sorting, but it now
971appears in a different position in the list due to the change of
972@sc{cdr}s. For example:
973
974@example
975@group
976(setq nums '(1 3 2 6 5 4 0))
977 @result{} (1 3 2 6 5 4 0)
978@end group
979@group
980(sort nums '<)
981 @result{} (0 1 2 3 4 5 6)
982@end group
983@group
984nums
985 @result{} (1 2 3 4 5 6)
986@end group
987@end example
988
989@noindent
990Note that the list in @code{nums} no longer contains 0; this is the same
991cons cell that it was before, but it is no longer the first one in the
992list. Don't assume a variable that formerly held the argument now holds
993the entire sorted list! Instead, save the result of @code{sort} and use
994that. Most often we store the result back into the variable that held
995the original list:
996
997@example
998(setq nums (sort nums '<))
999@end example
1000
1001@xref{Sorting}, for more functions that perform sorting.
1002See @code{documentation} in @ref{Accessing Documentation}, for a
1003useful example of @code{sort}.
1004@end defun
1005
1006@ifinfo
1007 See @code{delq}, in @ref{Sets And Lists}, for another function
1008that modifies cons cells.
1009@end ifinfo
1010@iftex
1011 The function @code{delq} in the following section is another example
1012of destructive list manipulation.
1013@end iftex
1014
1015@node Sets And Lists
1016@section Using Lists as Sets
1017@cindex lists as sets
1018@cindex sets
1019
1020 A list can represent an unordered mathematical set---simply consider a
1021value an element of a set if it appears in the list, and ignore the
1022order of the list. To form the union of two sets, use @code{append} (as
1023long as you don't mind having duplicate elements). Other useful
1024functions for sets include @code{memq} and @code{delq}, and their
1025@code{equal} versions, @code{member} and @code{delete}.
1026
1027@cindex CL note---lack @code{union}, @code{set}
1028@quotation
1029@b{Common Lisp note:} Common Lisp has functions @code{union} (which
1030avoids duplicate elements) and @code{intersection} for set operations,
1031but GNU Emacs Lisp does not have them. You can write them in Lisp if
1032you wish.
1033@end quotation
1034
1035@defun memq object list
1036@cindex membership in a list
1037This function tests to see whether @var{object} is a member of
1038@var{list}. If it is, @code{memq} returns a list starting with the
1039first occurrence of @var{object}. Otherwise, it returns @code{nil}.
1040The letter @samp{q} in @code{memq} says that it uses @code{eq} to
1041compare @var{object} against the elements of the list. For example:
1042
1043@example
1044@group
1045(memq 2 '(1 2 3 2 1))
1046 @result{} (2 3 2 1)
1047@end group
1048@group
1049(memq '(2) '((1) (2))) ; @r{@code{(2)} and @code{(2)} are not @code{eq}.}
1050 @result{} nil
1051@end group
1052@end example
1053@end defun
1054
1055@defun delq object list
1056@cindex deletion of elements
1057This function destructively removes all elements @code{eq} to
1058@var{object} from @var{list}. The letter @samp{q} in @code{delq} says
1059that it uses @code{eq} to compare @var{object} against the elements of
1060the list, like @code{memq}.
1061@end defun
1062
1063When @code{delq} deletes elements from the front of the list, it does so
1064simply by advancing down the list and returning a sublist that starts
1065after those elements:
1066
1067@example
1068@group
1069(delq 'a '(a b c)) @equiv{} (cdr '(a b c))
1070@end group
1071@end example
1072
1073When an element to be deleted appears in the middle of the list,
1074removing it involves changing the @sc{cdr}s (@pxref{Setcdr}).
1075
1076@example
1077@group
1078(setq sample-list '(1 2 3 (4)))
1079 @result{} (1 2 3 (4))
1080@end group
1081@group
1082(delq 1 sample-list)
1083 @result{} (2 3 (4))
1084@end group
1085@group
1086sample-list
1087 @result{} (1 2 3 (4))
1088@end group
1089@group
1090(delq 2 sample-list)
1091 @result{} (1 3 (4))
1092@end group
1093@group
1094sample-list
1095 @result{} (1 3 (4))
1096@end group
1097@end example
1098
1099Note that @code{(delq 2 sample-list)} modifies @code{sample-list} to
1100splice out the second element, but @code{(delq 1 sample-list)} does not
1101splice anything---it just returns a shorter list. Don't assume that a
1102variable which formerly held the argument @var{list} now has fewer
1103elements, or that it still holds the original list! Instead, save the
1104result of @code{delq} and use that. Most often we store the result back
1105into the variable that held the original list:
1106
1107@example
1108(setq flowers (delq 'rose flowers))
1109@end example
1110
1111In the following example, the @code{(4)} that @code{delq} attempts to match
1112and the @code{(4)} in the @code{sample-list} are not @code{eq}:
1113
1114@example
1115@group
1116(delq '(4) sample-list)
1117 @result{} (1 3 (4))
1118@end group
1119@end example
1120
1121The following two functions are like @code{memq} and @code{delq} but use
1122@code{equal} rather than @code{eq} to compare elements. They are new in
1123Emacs 19.
1124
1125@defun member object list
1126The function @code{member} tests to see whether @var{object} is a member
1127of @var{list}, comparing members with @var{object} using @code{equal}.
1128If @var{object} is a member, @code{member} returns a list starting with
1129its first occurrence in @var{list}. Otherwise, it returns @code{nil}.
1130
1131Compare this with @code{memq}:
1132
1133@example
1134@group
1135(member '(2) '((1) (2))) ; @r{@code{(2)} and @code{(2)} are @code{equal}.}
1136 @result{} ((2))
1137@end group
1138@group
1139(memq '(2) '((1) (2))) ; @r{@code{(2)} and @code{(2)} are not @code{eq}.}
1140 @result{} nil
1141@end group
1142@group
1143;; @r{Two strings with the same contents are @code{equal}.}
1144(member "foo" '("foo" "bar"))
1145 @result{} ("foo" "bar")
1146@end group
1147@end example
1148@end defun
1149
1150@defun delete object list
1151This function destructively removes all elements @code{equal} to
1152@var{object} from @var{list}. It is to @code{delq} as @code{member} is
1153to @code{memq}: it uses @code{equal} to compare elements with
1154@var{object}, like @code{member}; when it finds an element that matches,
1155it removes the element just as @code{delq} would. For example:
1156
1157@example
1158@group
1159(delete '(2) '((2) (1) (2)))
1160 @result{} '((1))
1161@end group
1162@end example
1163@end defun
1164
1165@quotation
1166@b{Common Lisp note:} The functions @code{member} and @code{delete} in
1167GNU Emacs Lisp are derived from Maclisp, not Common Lisp. The Common
1168Lisp versions do not use @code{equal} to compare elements.
1169@end quotation
1170
1171@node Association Lists
1172@section Association Lists
1173@cindex association list
1174@cindex alist
1175
1176 An @dfn{association list}, or @dfn{alist} for short, records a mapping
1177from keys to values. It is a list of cons cells called
1178@dfn{associations}: the @sc{car} of each cell is the @dfn{key}, and the
1179@sc{cdr} is the @dfn{associated value}.@footnote{This usage of ``key''
1180is not related to the term ``key sequence''; it means a value used to
1181look up an item in a table. In this case, the table is the alist, and
1182the alist associations are the items.}
1183
1184 Here is an example of an alist. The key @code{pine} is associated with
1185the value @code{cones}; the key @code{oak} is associated with
1186@code{acorns}; and the key @code{maple} is associated with @code{seeds}.
1187
1188@example
1189@group
1190'((pine . cones)
1191 (oak . acorns)
1192 (maple . seeds))
1193@end group
1194@end example
1195
1196 The associated values in an alist may be any Lisp objects; so may the
1197keys. For example, in the following alist, the symbol @code{a} is
1198associated with the number @code{1}, and the string @code{"b"} is
1199associated with the @emph{list} @code{(2 3)}, which is the @sc{cdr} of
1200the alist element:
1201
1202@example
1203((a . 1) ("b" 2 3))
1204@end example
1205
1206 Sometimes it is better to design an alist to store the associated
1207value in the @sc{car} of the @sc{cdr} of the element. Here is an
1208example:
1209
1210@example
1211'((rose red) (lily white) (buttercup yellow))
1212@end example
1213
1214@noindent
1215Here we regard @code{red} as the value associated with @code{rose}. One
1216advantage of this method is that you can store other related
1217information---even a list of other items---in the @sc{cdr} of the
1218@sc{cdr}. One disadvantage is that you cannot use @code{rassq} (see
1219below) to find the element containing a given value. When neither of
1220these considerations is important, the choice is a matter of taste, as
1221long as you are consistent about it for any given alist.
1222
1223 Note that the same alist shown above could be regarded as having the
1224associated value in the @sc{cdr} of the element; the value associated
1225with @code{rose} would be the list @code{(red)}.
1226
1227 Association lists are often used to record information that you might
1228otherwise keep on a stack, since new associations may be added easily to
1229the front of the list. When searching an association list for an
1230association with a given key, the first one found is returned, if there
1231is more than one.
1232
1233 In Emacs Lisp, it is @emph{not} an error if an element of an
1234association list is not a cons cell. The alist search functions simply
1235ignore such elements. Many other versions of Lisp signal errors in such
1236cases.
1237
1238 Note that property lists are similar to association lists in several
1239respects. A property list behaves like an association list in which
1240each key can occur only once. @xref{Property Lists}, for a comparison
1241of property lists and association lists.
1242
1243@defun assoc key alist
1244This function returns the first association for @var{key} in
1245@var{alist}. It compares @var{key} against the alist elements using
1246@code{equal} (@pxref{Equality Predicates}). It returns @code{nil} if no
1247association in @var{alist} has a @sc{car} @code{equal} to @var{key}.
1248For example:
1249
1250@smallexample
1251(setq trees '((pine . cones) (oak . acorns) (maple . seeds)))
1252 @result{} ((pine . cones) (oak . acorns) (maple . seeds))
1253(assoc 'oak trees)
1254 @result{} (oak . acorns)
1255(cdr (assoc 'oak trees))
1256 @result{} acorns
1257(assoc 'birch trees)
1258 @result{} nil
1259@end smallexample
1260
1261Here is another example in which the keys and values are not symbols:
1262
1263@smallexample
1264(setq needles-per-cluster
1265 '((2 "Austrian Pine" "Red Pine")
1266 (3 "Pitch Pine")
1267 (5 "White Pine")))
1268
1269(cdr (assoc 3 needles-per-cluster))
1270 @result{} ("Pitch Pine")
1271(cdr (assoc 2 needles-per-cluster))
1272 @result{} ("Austrian Pine" "Red Pine")
1273@end smallexample
1274@end defun
1275
1276@defun assq key alist
1277This function is like @code{assoc} in that it returns the first
1278association for @var{key} in @var{alist}, but it makes the comparison
1279using @code{eq} instead of @code{equal}. @code{assq} returns @code{nil}
1280if no association in @var{alist} has a @sc{car} @code{eq} to @var{key}.
1281This function is used more often than @code{assoc}, since @code{eq} is
1282faster than @code{equal} and most alists use symbols as keys.
1283@xref{Equality Predicates}.
1284
1285@smallexample
1286(setq trees '((pine . cones) (oak . acorns) (maple . seeds)))
1287 @result{} ((pine . cones) (oak . acorns) (maple . seeds))
1288(assq 'pine trees)
1289 @result{} (pine . cones)
1290@end smallexample
1291
1292On the other hand, @code{assq} is not usually useful in alists where the
1293keys may not be symbols:
1294
1295@smallexample
1296(setq leaves
1297 '(("simple leaves" . oak)
1298 ("compound leaves" . horsechestnut)))
1299
1300(assq "simple leaves" leaves)
1301 @result{} nil
1302(assoc "simple leaves" leaves)
1303 @result{} ("simple leaves" . oak)
1304@end smallexample
1305@end defun
1306
1307@defun rassq value alist
1308This function returns the first association with value @var{value} in
1309@var{alist}. It returns @code{nil} if no association in @var{alist} has
1310a @sc{cdr} @code{eq} to @var{value}.
1311
1312@code{rassq} is like @code{assq} except that it compares the @sc{cdr} of
1313each @var{alist} association instead of the @sc{car}. You can think of
1314this as ``reverse @code{assq}'', finding the key for a given value.
1315
1316For example:
1317
1318@smallexample
1319(setq trees '((pine . cones) (oak . acorns) (maple . seeds)))
1320
1321(rassq 'acorns trees)
1322 @result{} (oak . acorns)
1323(rassq 'spores trees)
1324 @result{} nil
1325@end smallexample
1326
1327Note that @code{rassq} cannot search for a value stored in the @sc{car}
1328of the @sc{cdr} of an element:
1329
1330@smallexample
1331(setq colors '((rose red) (lily white) (buttercup yellow)))
1332
1333(rassq 'white colors)
1334 @result{} nil
1335@end smallexample
1336
1337In this case, the @sc{cdr} of the association @code{(lily white)} is not
1338the symbol @code{white}, but rather the list @code{(white)}. This
1339becomes clearer if the association is written in dotted pair notation:
1340
1341@smallexample
1342(lily white) @equiv{} (lily . (white))
1343@end smallexample
1344@end defun
1345
1346@defun copy-alist alist
1347@cindex copying alists
1348This function returns a two-level deep copy of @var{alist}: it creates a
1349new copy of each association, so that you can alter the associations of
1350the new alist without changing the old one.
1351
1352@smallexample
1353@group
1354(setq needles-per-cluster
1355 '((2 . ("Austrian Pine" "Red Pine"))
1356 (3 . "Pitch Pine")
1357 (5 . "White Pine")))
1358@result{}
1359((2 "Austrian Pine" "Red Pine")
1360 (3 . "Pitch Pine")
1361 (5 . "White Pine"))
1362
1363(setq copy (copy-alist needles-per-cluster))
1364@result{}
1365((2 "Austrian Pine" "Red Pine")
1366 (3 . "Pitch Pine")
1367 (5 . "White Pine"))
1368
1369(eq needles-per-cluster copy)
1370 @result{} nil
1371(equal needles-per-cluster copy)
1372 @result{} t
1373(eq (car needles-per-cluster) (car copy))
1374 @result{} nil
1375(cdr (car (cdr needles-per-cluster)))
1376 @result{} "Pitch Pine"
1377(eq (cdr (car (cdr needles-per-cluster)))
1378 (cdr (car (cdr copy))))
1379 @result{} t
1380@end group
1381@end smallexample
1382@end defun
1383
1384
diff --git a/lispref/macros.texi b/lispref/macros.texi
new file mode 100644
index 00000000000..49d2d8e639d
--- /dev/null
+++ b/lispref/macros.texi
@@ -0,0 +1,593 @@
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/macros
6@node Macros, Loading, Functions, Top
7@chapter Macros
8@cindex macros
9
10 @dfn{Macros} enable you to define new control constructs and other
11language features. A macro is defined much like a function, but instead
12of telling how to compute a value, it tells how to compute another Lisp
13expression which will in turn compute the value. We call this
14expression the @dfn{expansion} of the macro.
15
16 Macros can do this because they operate on the unevaluated expressions
17for the arguments, not on the argument values as functions do. They can
18therefore construct an expansion containing these argument expressions
19or parts of them.
20
21 If you are using a macro to do something an ordinary function could
22do, just for the sake of speed, consider using an inline function
23instead. @xref{Inline Functions}.
24
25@menu
26* Simple Macro:: A basic example.
27* Expansion:: How, when and why macros are expanded.
28* Compiling Macros:: How macros are expanded by the compiler.
29* Defining Macros:: How to write a macro definition.
30* Backquote:: Easier construction of list structure.
31* Problems with Macros:: Don't evaluate the macro arguments too many times.
32 Don't hide the user's variables.
33@end menu
34
35@node Simple Macro
36@section A Simple Example of a Macro
37
38 Suppose we would like to define a Lisp construct to increment a
39variable value, much like the @code{++} operator in C. We would like to
40write @code{(inc x)} and have the effect of @code{(setq x (1+ x))}.
41Here's a macro definition that does the job:
42
43@findex inc
44@example
45@group
46(defmacro inc (var)
47 (list 'setq var (list '1+ var)))
48@end group
49@end example
50
51 When this is called with @code{(inc x)}, the argument @code{var} has
52the value @code{x}---@emph{not} the @emph{value} of @code{x}. The body
53of the macro uses this to construct the expansion, which is @code{(setq
54x (1+ x))}. Once the macro definition returns this expansion, Lisp
55proceeds to evaluate it, thus incrementing @code{x}.
56
57@node Expansion
58@section Expansion of a Macro Call
59@cindex expansion of macros
60@cindex macro call
61
62 A macro call looks just like a function call in that it is a list which
63starts with the name of the macro. The rest of the elements of the list
64are the arguments of the macro.
65
66 Evaluation of the macro call begins like evaluation of a function call
67except for one crucial difference: the macro arguments are the actual
68expressions appearing in the macro call. They are not evaluated before
69they are given to the macro definition. By contrast, the arguments of a
70function are results of evaluating the elements of the function call
71list.
72
73 Having obtained the arguments, Lisp invokes the macro definition just
74as a function is invoked. The argument variables of the macro are bound
75to the argument values from the macro call, or to a list of them in the
76case of a @code{&rest} argument. And the macro body executes and
77returns its value just as a function body does.
78
79 The second crucial difference between macros and functions is that the
80value returned by the macro body is not the value of the macro call.
81Instead, it is an alternate expression for computing that value, also
82known as the @dfn{expansion} of the macro. The Lisp interpreter
83proceeds to evaluate the expansion as soon as it comes back from the
84macro.
85
86 Since the expansion is evaluated in the normal manner, it may contain
87calls to other macros. It may even be a call to the same macro, though
88this is unusual.
89
90 You can see the expansion of a given macro call by calling
91@code{macroexpand}.
92
93@defun macroexpand form &optional environment
94@cindex macro expansion
95This function expands @var{form}, if it is a macro call. If the result
96is another macro call, it is expanded in turn, until something which is
97not a macro call results. That is the value returned by
98@code{macroexpand}. If @var{form} is not a macro call to begin with, it
99is returned as given.
100
101Note that @code{macroexpand} does not look at the subexpressions of
102@var{form} (although some macro definitions may do so). Even if they
103are macro calls themselves, @code{macroexpand} does not expand them.
104
105The function @code{macroexpand} does not expand calls to inline functions.
106Normally there is no need for that, since a call to an inline function is
107no harder to understand than a call to an ordinary function.
108
109If @var{environment} is provided, it specifies an alist of macro
110definitions that shadow the currently defined macros. Byte compilation
111uses this feature.
112
113@smallexample
114@group
115(defmacro inc (var)
116 (list 'setq var (list '1+ var)))
117 @result{} inc
118@end group
119
120@group
121(macroexpand '(inc r))
122 @result{} (setq r (1+ r))
123@end group
124
125@group
126(defmacro inc2 (var1 var2)
127 (list 'progn (list 'inc var1) (list 'inc var2)))
128 @result{} inc2
129@end group
130
131@group
132(macroexpand '(inc2 r s))
133 @result{} (progn (inc r) (inc s)) ; @r{@code{inc} not expanded here.}
134@end group
135@end smallexample
136@end defun
137
138@node Compiling Macros
139@section Macros and Byte Compilation
140@cindex byte-compiling macros
141
142 You might ask why we take the trouble to compute an expansion for a
143macro and then evaluate the expansion. Why not have the macro body
144produce the desired results directly? The reason has to do with
145compilation.
146
147 When a macro call appears in a Lisp program being compiled, the Lisp
148compiler calls the macro definition just as the interpreter would, and
149receives an expansion. But instead of evaluating this expansion, it
150compiles the expansion as if it had appeared directly in the program.
151As a result, the compiled code produces the value and side effects
152intended for the macro, but executes at full compiled speed. This would
153not work if the macro body computed the value and side effects
154itself---they would be computed at compile time, which is not useful.
155
156 In order for compilation of macro calls to work, the macros must be
157defined in Lisp when the calls to them are compiled. The compiler has a
158special feature to help you do this: if a file being compiled contains a
159@code{defmacro} form, the macro is defined temporarily for the rest of
160the compilation of that file. To use this feature, you must define the
161macro in the same file where it is used and before its first use.
162
163 Byte-compiling a file executes any @code{require} calls at top-level
164in the file. This is in case the file needs the required packages for
165proper compilation. One way to ensure that necessary macro definitions
166are available during compilation is to require the file that defines
167them. @xref{Features}.
168
169@node Defining Macros
170@section Defining Macros
171
172 A Lisp macro is a list whose @sc{car} is @code{macro}. Its @sc{cdr} should
173be a function; expansion of the macro works by applying the function
174(with @code{apply}) to the list of unevaluated argument-expressions
175from the macro call.
176
177 It is possible to use an anonymous Lisp macro just like an anonymous
178function, but this is never done, because it does not make sense to pass
179an anonymous macro to mapping functions such as @code{mapcar}. In
180practice, all Lisp macros have names, and they are usually defined with
181the special form @code{defmacro}.
182
183@defspec defmacro name argument-list body-forms@dots{}
184@code{defmacro} defines the symbol @var{name} as a macro that looks
185like this:
186
187@example
188(macro lambda @var{argument-list} . @var{body-forms})
189@end example
190
191This macro object is stored in the function cell of @var{name}. The
192value returned by evaluating the @code{defmacro} form is @var{name}, but
193usually we ignore this value.
194
195The shape and meaning of @var{argument-list} is the same as in a
196function, and the keywords @code{&rest} and @code{&optional} may be used
197(@pxref{Argument List}). Macros may have a documentation string, but
198any @code{interactive} declaration is ignored since macros cannot be
199called interactively.
200@end defspec
201
202@node Backquote
203@section Backquote
204@cindex backquote (list substitution)
205@cindex ` (list substitution)
206
207 Macros often need to construct large list structures from a mixture of
208constants and nonconstant parts. To make this easier, use the macro
209@code{`} (often called @dfn{backquote}).
210
211 Backquote allows you to quote a list, but selectively evaluate
212elements of that list. In the simplest case, it is identical to the
213special form @code{quote} (@pxref{Quoting}). For example, these
214two forms yield identical results:
215
216@example
217@group
218(` (a list of (+ 2 3) elements))
219 @result{} (a list of (+ 2 3) elements)
220@end group
221@group
222(quote (a list of (+ 2 3) elements))
223 @result{} (a list of (+ 2 3) elements)
224@end group
225@end example
226
227@findex , @{(with Backquote)}
228The special marker, @code{,}, inside of the argument to backquote,
229indicates a value that isn't constant. Backquote evaluates the
230argument of @code{,} and puts the value in the list structure:
231
232@example
233@group
234(list 'a 'list 'of (+ 2 3) 'elements)
235 @result{} (a list of 5 elements)
236@end group
237@group
238(` (a list of (, (+ 2 3)) elements))
239 @result{} (a list of 5 elements)
240@end group
241@end example
242
243@findex ,@@ @{(with Backquote)}
244@cindex splicing (with backquote)
245You can also @dfn{splice} an evaluated value into the resulting list,
246using the special marker @code{,@@}. The elements of the spliced list
247become elements at the same level as the other elements of the resulting
248list. The equivalent code without using @code{`} is often unreadable.
249Here are some examples:
250
251@example
252@group
253(setq some-list '(2 3))
254 @result{} (2 3)
255@end group
256@group
257(cons 1 (append some-list '(4) some-list))
258 @result{} (1 2 3 4 2 3)
259@end group
260@group
261(` (1 (,@@ some-list) 4 (,@@ some-list)))
262 @result{} (1 2 3 4 2 3)
263@end group
264
265@group
266(setq list '(hack foo bar))
267 @result{} (hack foo bar)
268@end group
269@group
270(cons 'use
271 (cons 'the
272 (cons 'words (append (cdr list) '(as elements)))))
273 @result{} (use the words foo bar as elements)
274@end group
275@group
276(` (use the words (,@@ (cdr list)) as elements))
277 @result{} (use the words foo bar as elements)
278@end group
279@end example
280
281Emacs 18 had a bug which made the previous example fail. The bug
282affected @code{,@@} followed only by constant elements. If you are
283concerned with Emacs 18 compatibility, you can work around the bug like
284this:
285
286@example
287(` (use the words (,@@ (cdr list)) as elements @code{(,@@ nil)}))
288@end example
289
290@noindent
291@code{(,@@ nil)} avoids the problem by being a nonconstant element that
292does not affect the result.
293
294@defmac ` list
295This macro quotes @var{list} except for any sublists of the form
296@code{(, @var{subexp})} or @code{(,@@ @var{listexp})}. Backquote
297replaces these sublists with the value of @var{subexp} (as a single
298element) or @var{listexp} (by splicing). Backquote copies the structure
299of @var{list} down to the places where variable parts are substituted.
300
301@ignore @c these work now!
302There are certain contexts in which @samp{,} would not be recognized and
303should not be used:
304
305@smallexample
306@group
307;; @r{Use of a @samp{,} expression as the @sc{cdr} of a list.}
308(` (a . (, 1))) ; @r{Not @code{(a . 1)}}
309 @result{} (a \, 1)
310@end group
311
312@group
313;; @r{Use of @samp{,} in a vector.}
314(` [a (, 1) c]) ; @r{Not @code{[a 1 c]}}
315 @error{} Wrong type argument
316@end group
317@end smallexample
318@end ignore
319@end defmac
320
321@cindex CL note---@samp{,}, @samp{,@@} as functions
322@quotation
323@b{Common Lisp note:} in Common Lisp, @samp{,} and @samp{,@@} are implemented
324as reader macros, so they do not require parentheses. Emacs Lisp implements
325them as functions because reader macros are not supported (to save space).
326@end quotation
327
328@node Problems with Macros
329@section Common Problems Using Macros
330
331 The basic facts of macro expansion have counterintuitive consequences.
332This section describes some important consequences that can lead to
333trouble, and rules to follow to avoid trouble.
334
335@menu
336* Argument Evaluation:: The expansion should evaluate each macro arg once.
337* Surprising Local Vars:: Local variable bindings in the expansion
338 require special care.
339* Eval During Expansion:: Don't evaluate them; put them in the expansion.
340* Repeated Expansion:: Avoid depending on how many times expansion is done.
341@end menu
342
343@node Argument Evaluation
344@subsection Evaluating Macro Arguments Repeatedly
345
346 When defining a macro you must pay attention to the number of times
347the arguments will be evaluated when the expansion is executed. The
348following macro (used to facilitate iteration) illustrates the problem.
349This macro allows us to write a simple ``for'' loop such as one might
350find in Pascal.
351
352@findex for
353@smallexample
354@group
355(defmacro for (var from init to final do &rest body)
356 "Execute a simple \"for\" loop.
357For example, (for i from 1 to 10 do (print i))."
358 (list 'let (list (list var init))
359 (cons 'while (cons (list '<= var final)
360 (append body (list (list 'inc var)))))))
361@end group
362@result{} for
363
364@group
365(for i from 1 to 3 do
366 (setq square (* i i))
367 (princ (format "\n%d %d" i square)))
368@expansion{}
369@end group
370@group
371(let ((i 1))
372 (while (<= i 3)
373 (setq square (* i i))
374 (princ (format "%d %d" i square))
375 (inc i)))
376@end group
377@group
378
379 @print{}1 1
380 @print{}2 4
381 @print{}3 9
382@result{} nil
383@end group
384@end smallexample
385
386@noindent
387(The arguments @code{from}, @code{to}, and @code{do} in this macro are
388``syntactic sugar''; they are entirely ignored. The idea is that you
389will write noise words (such as @code{from}, @code{to}, and @code{do})
390in those positions in the macro call.)
391
392This macro suffers from the defect that @var{final} is evaluated on
393every iteration. If @var{final} is a constant, this is not a problem.
394If it is a more complex form, say @code{(long-complex-calculation x)},
395this can slow down the execution significantly. If @var{final} has side
396effects, executing it more than once is probably incorrect.
397
398@cindex macro argument evaluation
399A well-designed macro definition takes steps to avoid this problem by
400producing an expansion that evaluates the argument expressions exactly
401once unless repeated evaluation is part of the intended purpose of the
402macro. Here is a correct expansion for the @code{for} macro:
403
404@smallexample
405@group
406(let ((i 1)
407 (max 3))
408 (while (<= i max)
409 (setq square (* i i))
410 (princ (format "%d %d" i square))
411 (inc i)))
412@end group
413@end smallexample
414
415Here is a macro definition that creates this expansion:
416
417@smallexample
418@group
419(defmacro for (var from init to final do &rest body)
420 "Execute a simple for loop: (for i from 1 to 10 do (print i))."
421 (` (let (((, var) (, init))
422 (max (, final)))
423 (while (<= (, var) max)
424 (,@@ body)
425 (inc (, var))))))
426@end group
427@end smallexample
428
429 Unfortunately, this introduces another problem.
430@ifinfo
431Proceed to the following node.
432@end ifinfo
433
434@node Surprising Local Vars
435@subsection Local Variables in Macro Expansions
436
437@ifinfo
438 In the previous section, the definition of @code{for} was fixed as
439follows to make the expansion evaluate the macro arguments the proper
440number of times:
441
442@smallexample
443@group
444(defmacro for (var from init to final do &rest body)
445 "Execute a simple for loop: (for i from 1 to 10 do (print i))."
446@end group
447@group
448 (` (let (((, var) (, init))
449 (max (, final)))
450 (while (<= (, var) max)
451 (,@@ body)
452 (inc (, var))))))
453@end group
454@end smallexample
455@end ifinfo
456
457 The new definition of @code{for} has a new problem: it introduces a
458local variable named @code{max} which the user does not expect. This
459causes trouble in examples such as the following:
460
461@example
462@group
463(let ((max 0))
464 (for x from 0 to 10 do
465 (let ((this (frob x)))
466 (if (< max this)
467 (setq max this)))))
468@end group
469@end example
470
471@noindent
472The references to @code{max} inside the body of the @code{for}, which
473are supposed to refer to the user's binding of @code{max}, really access
474the binding made by @code{for}.
475
476The way to correct this is to use an uninterned symbol instead of
477@code{max} (@pxref{Creating Symbols}). The uninterned symbol can be
478bound and referred to just like any other symbol, but since it is created
479by @code{for}, we know that it cannot appear in the user's program.
480Since it is not interned, there is no way the user can put it into the
481program later. It will never appear anywhere except where put by
482@code{for}. Here is a definition of @code{for} which works this way:
483
484@smallexample
485@group
486(defmacro for (var from init to final do &rest body)
487 "Execute a simple for loop: (for i from 1 to 10 do (print i))."
488 (let ((tempvar (make-symbol "max")))
489 (` (let (((, var) (, init))
490 ((, tempvar) (, final)))
491 (while (<= (, var) (, tempvar))
492 (,@@ body)
493 (inc (, var)))))))
494@end group
495@end smallexample
496
497@noindent
498This creates an uninterned symbol named @code{max} and puts it in the
499expansion instead of the usual interned symbol @code{max} that appears
500in expressions ordinarily.
501
502@node Eval During Expansion
503@subsection Evaluating Macro Arguments in Expansion
504
505 Another problem can happen if you evaluate any of the macro argument
506expressions during the computation of the expansion, such as by calling
507@code{eval} (@pxref{Eval}). If the argument is supposed to refer to the
508user's variables, you may have trouble if the user happens to use a
509variable with the same name as one of the macro arguments. Inside the
510macro body, the macro argument binding is the most local binding of this
511variable, so any references inside the form being evaluated do refer
512to it. Here is an example:
513
514@example
515@group
516(defmacro foo (a)
517 (list 'setq (eval a) t))
518 @result{} foo
519@end group
520@group
521(setq x 'b)
522(foo x) @expansion{} (setq b t)
523 @result{} t ; @r{and @code{b} has been set.}
524;; @r{but}
525(setq a 'c)
526(foo a) @expansion{} (setq a t)
527 @result{} t ; @r{but this set @code{a}, not @code{c}.}
528
529@end group
530@end example
531
532 It makes a difference whether the user's variable is named @code{a} or
533@code{x}, because @code{a} conflicts with the macro argument variable
534@code{a}.
535
536 Another reason not to call @code{eval} in a macro definition is that
537it probably won't do what you intend in a compiled program. The
538byte-compiler runs macro definitions while compiling the program, when
539the program's own computations (which you might have wished to access
540with @code{eval}) don't occur and its local variable bindings don't
541exist.
542
543 The safe way to work with the run-time value of an expression is to
544put the expression into the macro expansion, so that its value is
545computed as part of executing the expansion.
546
547@node Repeated Expansion
548@subsection How Many Times is the Macro Expanded?
549
550 Occasionally problems result from the fact that a macro call is
551expanded each time it is evaluated in an interpreted function, but is
552expanded only once (during compilation) for a compiled function. If the
553macro definition has side effects, they will work differently depending
554on how many times the macro is expanded.
555
556 In particular, constructing objects is a kind of side effect. If the
557macro is called once, then the objects are constructed only once. In
558other words, the same structure of objects is used each time the macro
559call is executed. In interpreted operation, the macro is reexpanded
560each time, producing a fresh collection of objects each time. Usually
561this does not matter---the objects have the same contents whether they
562are shared or not. But if the surrounding program does side effects
563on the objects, it makes a difference whether they are shared. Here is
564an example:
565
566@lisp
567@group
568(defmacro empty-object ()
569 (list 'quote (cons nil nil)))
570@end group
571
572@group
573(defun initialize (condition)
574 (let ((object (empty-object)))
575 (if condition
576 (setcar object condition))
577 object))
578@end group
579@end lisp
580
581@noindent
582If @code{initialize} is interpreted, a new list @code{(nil)} is
583constructed each time @code{initialize} is called. Thus, no side effect
584survives between calls. If @code{initialize} is compiled, then the
585macro @code{empty-object} is expanded during compilation, producing a
586single ``constant'' @code{(nil)} that is reused and altered each time
587@code{initialize} is called.
588
589One way to avoid pathological cases like this is to think of
590@code{empty-object} as a funny kind of constant, not as a memory
591allocation construct. You wouldn't use @code{setcar} on a constant such
592as @code{'(nil)}, so naturally you won't use it on @code{(empty-object)}
593either.
diff --git a/lispref/os.texi b/lispref/os.texi
new file mode 100644
index 00000000000..533c3a7f4ac
--- /dev/null
+++ b/lispref/os.texi
@@ -0,0 +1,1355 @@
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/os
6@node System Interface, Display, Processes, Top
7@chapter Operating System Interface
8
9 This chapter is about starting and getting out of Emacs, access to
10values in the operating system environment, and terminal input, output
11and flow control.
12
13 @xref{Building Emacs}, for related information. See also
14@ref{Display}, for additional operating system status information
15pertaining to the terminal and the screen.
16
17@menu
18* Starting Up:: Customizing Emacs start-up processing.
19* Getting Out:: How exiting works (permanent or temporary).
20* System Environment:: Distinguish the name and kind of system.
21* User Identification:: Finding the name and user id of the user.
22* Time of Day:: Getting the current time.
23* Timers:: Setting a timer to call a function at a certain time.
24* Terminal Input:: Recording terminal input for debugging.
25* Terminal Output:: Recording terminal output for debugging.
26* Special Keysyms:: Defining system-specific key symbols for X windows.
27* Flow Control:: How to turn output flow control on or off.
28* Batch Mode:: Running Emacs without terminal interaction.
29@end menu
30
31@node Starting Up
32@section Starting Up Emacs
33
34 This section describes what Emacs does when it is started, and how you
35can customize these actions.
36
37@menu
38* Start-up Summary:: Sequence of actions Emacs performs at start-up.
39* Init File:: Details on reading the init file (@file{.emacs}).
40* Terminal-Specific:: How the terminal-specific Lisp file is read.
41* Command Line Arguments:: How command line arguments are processed,
42 and how you can customize them.
43@end menu
44
45@node Start-up Summary
46@subsection Summary: Sequence of Actions at Start Up
47@cindex initialization
48@cindex start up of Emacs
49@cindex @file{startup.el}
50
51 The order of operations performed (in @file{startup.el}) by Emacs when
52it is started up is as follows:
53
54@enumerate
55@item
56It loads the initialization library for the window system, if you are
57using a window system. This library's name is
58@file{term/@var{windowsystem}-win.el}.
59
60@item
61It initializes the X window frame and faces, if appropriate.
62
63@item
64It runs the normal hook @code{before-init-hook}.
65
66@item
67It loads the library @file{site-start}, unless the option
68@samp{-no-site-file} was specified. The library's file name is usually
69@file{site-start.el}.
70@cindex @file{site-start.el}
71
72@item
73It loads the file @file{~/.emacs} unless @samp{-q} was specified on
74command line. (This is not done in @samp{-batch} mode.) The @samp{-u}
75option can specify the user name whose home directory should be used
76instead of @file{~}.
77
78@item
79It loads the library @file{default} unless @code{inhibit-default-init}
80is non-@code{nil}. (This is not done in @samp{-batch} mode or if
81@samp{-q} was specified on command line.) The library's file name is
82usually @file{default.el}.
83@cindex @file{default.el}
84
85@item
86It runs the normal hook @code{after-init-hook}.
87
88@item
89It sets the major mode according to @code{initial-major-mode}, provided
90the buffer @samp{*scratch*} is still current and still in Fundamental
91mode.
92
93@item
94It loads the terminal-specific Lisp file, if any, except when in batch
95mode or using a window system.
96
97@item
98It displays the initial echo area message, unless you have suppressed
99that with @code{inhibit-startup-echo-area-message}.
100
101@item
102It processes any remaining command line arguments.
103
104@item
105It runs @code{term-setup-hook}.
106
107@item
108It calls @code{frame-notice-user-settings}, which modifies the
109parameters of the selected frame according to whatever the init files
110specify.
111
112@item
113It runs @code{window-setup-hook}. @xref{Window Systems}.
114
115@item
116It displays copyleft, nonwarranty and basic use information, provided
117there were no remaining command line arguments (a few steps above) and
118the value of @code{inhibit-startup-message} is @code{nil}.
119@end enumerate
120
121@defopt inhibit-startup-message
122This variable inhibits the initial startup messages (the nonwarranty,
123etc.). If it is non-@code{nil}, then the messages are not printed.
124
125This variable exists so you can set it in your personal init file, once
126you are familiar with the contents of the startup message. Do not set
127this variable in the init file of a new user, or in a way that affects
128more than one user, because that would prevent new users from receiving
129the information they are supposed to see.
130@end defopt
131
132@defopt inhibit-startup-echo-area-message
133This variable controls the display of the startup echo area message.
134You can suppress the startup echo area message by adding text with this
135form to your @file{.emacs} file:
136
137@example
138(setq inhibit-startup-echo-area-message
139 "@var{your-login-name}")
140@end example
141
142Simply setting @code{inhibit-startup-echo-area-message} to your login
143name is not sufficient to inhibit the message; Emacs explicitly checks
144whether @file{.emacs} contains an expression as shown above. Your login
145name must appear in the expression as a Lisp string constant.
146
147This way, you can easily inhibit the message for yourself if you wish,
148but thoughtless copying of your @file{.emacs} file will not inhibit the
149message for someone else.
150@end defopt
151
152@node Init File
153@subsection The Init File: @file{.emacs}
154@cindex init file
155@cindex @file{.emacs}
156
157 When you start Emacs, it normally attempts to load the file
158@file{.emacs} from your home directory. This file, if it exists, must
159contain Lisp code. It is called your @dfn{init file}. The command line
160switches @samp{-q} and @samp{-u} affect the use of the init file;
161@samp{-q} says not to load an init file, and @samp{-u} says to load a
162specified user's init file instead of yours. @xref{Entering Emacs, , ,
163emacs, The GNU Emacs Manual}.
164
165@cindex default init file
166 A site may have a @dfn{default init file}, which is the library named
167@file{default.el}. Emacs finds the @file{default.el} file through the
168standard search path for libraries (@pxref{How Programs Do Loading}).
169The Emacs distribution does not come with this file; sites may provide
170one for local customizations. If the default init file exists, it is
171loaded whenever you start Emacs, except in batch mode or if @samp{-q} is
172specified. But your own personal init file, if any, is loaded first; if
173it sets @code{inhibit-default-init} to a non-@code{nil} value, then
174Emacs does not subsequently load the @file{default.el} file.
175
176 Another file for site-customization is @file{site-start.el}. Emacs
177loads this @emph{before} the user's init file. You can inhibit the
178loading of this file with the option @samp{-no-site-file}.
179
180 If there is a great deal of code in your @file{.emacs} file, you
181should move it into another file named @file{@var{something}.el},
182byte-compile it (@pxref{Byte Compilation}), and make your @file{.emacs}
183file load the other file using @code{load} (@pxref{Loading}).
184
185 @xref{Init File Examples, , , emacs, The GNU Emacs Manual}, for
186examples of how to make various commonly desired customizations in your
187@file{.emacs} file.
188
189@defopt inhibit-default-init
190This variable prevents Emacs from loading the default initialization
191library file for your session of Emacs. If its value is non-@code{nil},
192then the default library is not loaded. The default value is
193@code{nil}.
194@end defopt
195
196@defvar before-init-hook
197@defvarx after-init-hook
198These two normal hooks are run just before, and just after, loading of
199the user's init file, @file{default.el}, and/or @file{site-start.el}.
200@end defvar
201
202@node Terminal-Specific
203@subsection Terminal-Specific Initialization
204@cindex terminal-specific initialization
205
206 Each terminal type can have its own Lisp library that Emacs loads when
207run on that type of terminal. For a terminal type named @var{termtype},
208the library is called @file{term/@var{termtype}}. Emacs finds the file
209by searching the @code{load-path} directories as it does for other
210files, and trying the @samp{.elc} and @samp{.el} suffixes. Normally,
211terminal-specific Lisp library is located in @file{emacs/lisp/term}, a
212subdirectory of the @file{emacs/lisp} directory in which most Emacs Lisp
213libraries are kept.@refill
214
215 The library's name is constructed by concatenating the value of the
216variable @code{term-file-prefix} and the terminal type. Normally,
217@code{term-file-prefix} has the value @code{"term/"}; changing this
218is not recommended.
219
220 The usual function of a terminal-specific library is to enable special
221keys to send sequences that Emacs can recognize. It may also need to
222set or add to @code{function-key-map} if the Termcap entry does not
223specify all the terminal's function keys. @xref{Terminal Input}.
224
225@cindex Termcap
226 When the name of the terminal type contains a hyphen, only the part of
227the name before the first hyphen is significant in choosing the library
228name. Thus, terminal types @samp{aaa-48} and @samp{aaa-30-rv} both use
229the @file{term/aaa} library. If necessary, the library can evaluate
230@code{(getenv "TERM")} to find the full name of the terminal
231type.@refill
232
233 Your @file{.emacs} file can prevent the loading of the
234terminal-specific library by setting the variable
235@code{term-file-prefix} to @code{nil}. This feature is useful when
236experimenting with your own peculiar customizations.
237
238 You can also arrange to override some of the actions of the
239terminal-specific library by setting the variable
240@code{term-setup-hook}. This is a normal hook which Emacs runs using
241@code{run-hooks} at the end of Emacs initialization, after loading both
242your @file{.emacs} file and any terminal-specific libraries. You can
243use this variable to define initializations for terminals that do not
244have their own libraries. @xref{Hooks}.
245
246@defvar term-file-prefix
247@cindex @code{TERM} environment variable
248If the @code{term-file-prefix} variable is non-@code{nil}, Emacs loads
249a terminal-specific initialization file as follows:
250
251@example
252(load (concat term-file-prefix (getenv "TERM")))
253@end example
254
255@noindent
256You may set the @code{term-file-prefix} variable to @code{nil} in your
257@file{.emacs} file if you do not wish to load the
258terminal-initialization file. To do this, put the following in
259your @file{.emacs} file: @code{(setq term-file-prefix nil)}.
260@end defvar
261
262@defvar term-setup-hook
263This variable is a normal hook which Emacs runs after loading your
264@file{.emacs} file, the default initialization file (if any) and the
265terminal-specific Lisp file.
266
267You can use @code{term-setup-hook} to override the definitions made by a
268terminal-specific file.
269@end defvar
270
271 See @code{window-setup-hook} in @ref{Window Systems}, for a related
272feature.
273
274@node Command Line Arguments
275@subsection Command Line Arguments
276@cindex command line arguments
277
278 You can use command line arguments to request various actions when you
279start Emacs. Since you do not need to start Emacs more than once per
280day, and will often leave your Emacs session running longer than that,
281command line arguments are hardly ever used. As a practical matter, it
282is best to avoid making the habit of using them, since this habit would
283encourage you to kill and restart Emacs unnecessarily often. These
284options exist for two reasons: to be compatible with other editors (for
285invocation by other programs) and to enable shell scripts to run
286specific Lisp programs.
287
288 This section describes how Emacs processes command line arguments,
289and how you can customize them.
290
291@ignore
292 (Note that some other editors require you to start afresh each time
293you want to edit a file. With this kind of editor, you will probably
294specify the file as a command line argument. The recommended way to
295use GNU Emacs is to start it only once, just after you log in, and do
296all your editing in the same Emacs process. Each time you want to edit
297a different file, you visit it with the existing Emacs, which eventually
298comes to have many files in it ready for editing. Usually you do not
299kill the Emacs until you are about to log out.)
300@end ignore
301
302@defun command-line
303This function parses the command line which Emacs was called with,
304processes it, loads the user's @file{.emacs} file and displays the
305initial nonwarranty information, etc.
306@end defun
307
308@defvar command-line-processed
309The value of this variable is @code{t} once the command line has been
310processed.
311
312If you redump Emacs by calling @code{dump-emacs}, you may wish to set
313this variable to @code{nil} first in order to cause the new dumped Emacs
314to process its new command line arguments.
315@end defvar
316
317@defvar command-switch-alist
318@cindex switches on command line
319@cindex options on command line
320@cindex command line options
321The value of this variable is an alist of user-defined command-line
322options and associated handler functions. This variable exists so you
323can add elements to it.
324
325A @dfn{command line option} is an argument on the command line of the
326form:
327
328@example
329-@var{option}
330@end example
331
332The elements of the @code{command-switch-alist} look like this:
333
334@example
335(@var{option} . @var{handler-function})
336@end example
337
338The @var{handler-function} is called to handle @var{option} and receives
339the option name as its sole argument.
340
341In some cases, the option is followed in the command line by an
342argument. In these cases, the @var{handler-function} can find all the
343remaining command-line arguments in the variable
344@code{command-line-args-left}. (The entire list of command-line
345arguments is in @code{command-line-args}.)
346
347The command line arguments are parsed by the @code{command-line-1}
348function in the @file{startup.el} file. See also @ref{Command
349Switches, , Command Line Switches and Arguments, emacs, The GNU Emacs
350Manual}.
351@end defvar
352
353@defvar command-line-args
354The value of this variable is the list of command line arguments passed
355to Emacs.
356@end defvar
357
358@defvar command-line-functions
359This variable's value is a list of functions for handling an
360unrecognized command-line argument. Each time the next argument to be
361processed has no special meaning, the functions in this list are called,
362in the order they appear, until one of them returns a non-@code{nil}
363value.
364
365These functions are called with no arguments. They can access the
366command-line argument under consideration through the variable
367@code{argi}. The remaining arguments (not including the current one)
368are in the variable @code{command-line-args-left}.
369
370When a function recognizes and processes the argument in @code{argi}, it
371should return a non-@code{nil} value to say it has dealt with that
372argument. If it has also dealt with some of the following arguments, it
373can indicate that by deleting them from @code{command-line-args-left}.
374
375If all of these functions return @code{nil}, then the argument is used
376as a file name to visit.
377@end defvar
378
379@node Getting Out
380@section Getting Out of Emacs
381@cindex exiting Emacs
382
383 There are two ways to get out of Emacs: you can kill the Emacs job,
384which exits permanently, or you can suspend it, which permits you to
385reenter the Emacs process later. As a practical matter, you seldom kill
386Emacs---only when you are about to log out. Suspending is much more
387common.
388
389@menu
390* Killing Emacs:: Exiting Emacs irreversibly.
391* Suspending Emacs:: Exiting Emacs reversibly.
392@end menu
393
394@node Killing Emacs
395@comment node-name, next, previous, up
396@subsection Killing Emacs
397@cindex killing Emacs
398
399 Killing Emacs means ending the execution of the Emacs process. The
400parent process normally resumes control. The low-level primitive for
401killing Emacs is @code{kill-emacs}.
402
403@defun kill-emacs &optional exit-data
404This function exits the Emacs process and kills it.
405
406If @var{exit-data} is an integer, then it is used as the exit status
407of the Emacs process. (This is useful primarily in batch operation; see
408@ref{Batch Mode}.)
409
410If @var{exit-data} is a string, its contents are stuffed into the
411terminal input buffer so that the shell (or whatever program next reads
412input) can read them.
413@end defun
414
415 All the information in the Emacs process, aside from files that have
416been saved, is lost when the Emacs is killed. Because killing Emacs
417inadvertently can lose a lot of work, Emacs queries for confirmation
418before actually terminating if you have buffers that need saving or
419subprocesses that are running. This is done in the function
420@code{save-buffers-kill-emacs}.
421
422@defvar kill-emacs-query-functions
423After asking the standard questions, @code{save-buffers-kill-emacs}
424calls the functions in the list @code{kill-buffer-query-functions}, in
425order of appearance, with no arguments. These functions can ask for
426additional confirmation from the user. If any of them returns
427non-@code{nil}, Emacs is not killed.
428@end defvar
429
430@defvar kill-emacs-hook
431This variable is a normal hook; once @code{save-buffers-kill-emacs} is
432finished with all file saving and confirmation, it runs the functions in
433this hook.
434@end defvar
435
436@node Suspending Emacs
437@subsection Suspending Emacs
438@cindex suspending Emacs
439
440 @dfn{Suspending Emacs} means stopping Emacs temporarily and returning
441control to its superior process, which is usually the shell. This
442allows you to resume editing later in the same Emacs process, with the
443same buffers, the same kill ring, the same undo history, and so on. To
444resume Emacs, use the appropriate command in the parent shell---most
445likely @code{fg}.
446
447 Some operating systems do not support suspension of jobs; on these
448systems, ``suspension'' actually creates a new shell temporarily as a
449subprocess of Emacs. Then you would exit the shell to return to Emacs.
450
451 Suspension is not useful with window systems such as X, because the
452Emacs job may not have a parent that can resume it again, and in any
453case you can give input to some other job such as a shell merely by
454moving to a different window. Therefore, suspending is not allowed
455when Emacs is an X client.
456
457@defun suspend-emacs string
458This function stops Emacs and returns control to the superior process.
459If and when the superior process resumes Emacs, @code{suspend-emacs}
460returns @code{nil} to its caller in Lisp.
461
462If @var{string} is non-@code{nil}, its characters are sent to be read
463as terminal input by Emacs's superior shell. The characters in
464@var{string} are not echoed by the superior shell; only the results
465appear.
466
467Before suspending, @code{suspend-emacs} runs the normal hook
468@code{suspend-hook}. In Emacs version 18, @code{suspend-hook} was not a
469normal hook; its value was a single function, and if its value was
470non-@code{nil}, then @code{suspend-emacs} returned immediately without
471actually suspending anything.
472
473After the user resumes Emacs, it runs the normal hook
474@code{suspend-resume-hook}. @xref{Hooks}.
475
476The next redisplay after resumption will redraw the entire screen,
477unless the variable @code{no-redraw-on-reenter} is non-@code{nil}
478(@pxref{Refresh Screen}).
479
480In the following example, note that @samp{pwd} is not echoed after
481Emacs is suspended. But it is read and executed by the shell.
482
483@smallexample
484@group
485(suspend-emacs)
486 @result{} nil
487@end group
488
489@group
490(add-hook 'suspend-hook
491 (function (lambda ()
492 (or (y-or-n-p
493 "Really suspend? ")
494 (error "Suspend cancelled")))))
495 @result{} (lambda nil
496 (or (y-or-n-p "Really suspend? ")
497 (error "Suspend cancelled")))
498@end group
499@group
500(add-hook 'suspend-resume-hook
501 (function (lambda () (message "Resumed!"))))
502 @result{} (lambda nil (message "Resumed!"))
503@end group
504@group
505(suspend-emacs "pwd")
506 @result{} nil
507@end group
508@group
509---------- Buffer: Minibuffer ----------
510Really suspend? @kbd{y}
511---------- Buffer: Minibuffer ----------
512@end group
513
514@group
515---------- Parent Shell ----------
516lewis@@slug[23] % /user/lewis/manual
517lewis@@slug[24] % fg
518@end group
519
520@group
521---------- Echo Area ----------
522Resumed!
523@end group
524@end smallexample
525@end defun
526
527@defvar suspend-hook
528This variable is a normal hook run before suspending.
529@end defvar
530
531@defvar suspend-resume-hook
532This variable is a normal hook run after suspending.
533@end defvar
534
535@node System Environment
536@section Operating System Environment
537@cindex operating system environment
538
539 Emacs provides access to variables in the operating system environment
540through various functions. These variables include the name of the
541system, the user's @sc{uid}, and so on.
542
543@defvar system-type
544The value of this variable is a symbol indicating the type of
545operating system Emacs is operating on. Here is a table of the symbols
546for the operating systems that Emacs can run on up to version 19.1.
547
548@table @code
549@item aix-v3
550AIX.
551
552@item berkeley-unix
553Berkeley BSD.
554
555@item hpux
556Hewlett-Packard operating system.
557
558@item irix
559Silicon Graphics Irix system.
560
561@item rtu
562Masscomp RTU, UCB universe.
563
564@item unisoft-unix
565UniSoft UniPlus.
566
567@item usg-unix-v
568AT&T System V.
569
570@item vax-vms
571VAX VMS.
572
573@item xenix
574SCO Xenix 386.
575@end table
576
577We do not wish to add new symbols to make finer distinctions unless it
578is absolutely necessary! In fact, we hope to eliminate some of these
579alternatives in the future. We recommend using
580@code{system-configuration} to distinguish between different operating
581systems.
582@end defvar
583
584@defvar system-configuration
585This variable holds the three-part configuration name for the
586hardware/software configuration of your system, as a string. The
587convenient way to test parts of this string is with @code{string-match}.
588@end defvar
589
590@defun system-name
591This function returns the name of the machine you are running on.
592@example
593(system-name)
594 @result{} "prep.ai.mit.edu"
595@end example
596@end defun
597
598@defun getenv var
599@cindex environment variable access
600This function returns the value of the environment variable @var{var},
601as a string. Within Emacs, the environment variable values are kept in
602the Lisp variable @code{process-environment}.
603
604@example
605@group
606(getenv "USER")
607 @result{} "lewis"
608@end group
609
610@group
611lewis@@slug[10] % printenv
612PATH=.:/user/lewis/bin:/usr/bin:/usr/local/bin
613USER=lewis
614@end group
615@group
616TERM=ibmapa16
617SHELL=/bin/csh
618HOME=/user/lewis
619@end group
620@end example
621@end defun
622
623@c Emacs 19 feature
624@deffn Command setenv variable value
625This command sets the value of the environment variable named
626@var{variable} to @var{value}. Both arguments should be strings. This
627function works by modifying @code{process-environment}; binding that
628variable with @code{let} is also reasonable practice.
629@end deffn
630
631@defvar process-environment
632This variable is a list of strings, each describing one environment
633variable. The functions @code{getenv} and @code{setenv} work by means
634of this variable.
635
636@smallexample
637@group
638process-environment
639@result{} ("l=/usr/stanford/lib/gnuemacs/lisp"
640 "PATH=.:/user/lewis/bin:/usr/class:/nfsusr/local/bin"
641 "USER=lewis"
642@end group
643@group
644 "TERM=ibmapa16"
645 "SHELL=/bin/csh"
646 "HOME=/user/lewis")
647@end group
648@end smallexample
649@end defvar
650
651@defun load-average
652This function returns the current 1 minute, 5 minute and 15 minute
653load averages in a list. The values are integers that are 100 times
654the system load averages. (The load averages indicate the number of
655processes trying to run.)
656
657@example
658@group
659(load-average)
660 @result{} (169 48 36)
661@end group
662
663@group
664lewis@@rocky[5] % uptime
665 11:55am up 1 day, 19:37, 3 users,
666 load average: 1.69, 0.48, 0.36
667@end group
668@end example
669@end defun
670
671@defun emacs-pid
672This function returns the process @sc{id} of the Emacs process.
673@end defun
674
675@defun setprv privilege-name &optional setp getprv
676This function sets or resets a VMS privilege. (It does not exist on
677Unix.) The first arg is the privilege name, as a string. The second
678argument, @var{setp}, is @code{t} or @code{nil}, indicating whether the
679privilege is to be turned on or off. Its default is @code{nil}. The
680function returns @code{t} if successful, @code{nil} otherwise.
681
682 If the third argument, @var{getprv}, is non-@code{nil}, @code{setprv}
683does not change the privilege, but returns @code{t} or @code{nil}
684indicating whether the privilege is currently enabled.
685@end defun
686
687@node User Identification
688@section User Identification
689
690@defun user-login-name
691This function returns the name under which the user is logged in. If
692the environment variable @code{LOGNAME} is set, that value is used.
693Otherwise, if the environment variable @code{USER} is set, that value is
694used. Otherwise, the value is based on the effective @sc{uid}, not the
695real @sc{uid}.
696
697@example
698@group
699(user-login-name)
700 @result{} "lewis"
701@end group
702@end example
703@end defun
704
705@defun user-real-login-name
706This function returns the user name corresponding to Emacs's real
707@sc{uid}. This ignores the effective @sc{uid} and ignores the
708environment variables @code{LOGNAME} and @code{USER}.
709@end defun
710
711@defun user-full-name
712This function returns the full name of the user.
713
714@example
715@group
716(user-full-name)
717 @result{} "Bil Lewis"
718@end group
719@end example
720@end defun
721
722@defun user-real-uid
723This function returns the real @sc{uid} of the user.
724
725@example
726@group
727(user-real-uid)
728 @result{} 19
729@end group
730@end example
731@end defun
732
733@defun user-uid
734This function returns the effective @sc{uid} of the user.
735@end defun
736
737@node Time of Day
738@section Time of Day
739
740 This section explains how to determine the current time and the time
741zone.
742
743@defun current-time-string &optional time-value
744This function returns the current time and date as a humanly-readable
745string. The format of the string is unvarying; the number of characters
746used for each part is always the same, so you can reliably use
747@code{substring} to extract pieces of it. However, it would be wise to
748count the characters from the beginning of the string rather than from
749the end, as additional information may be added at the end.
750
751@c Emacs 19 feature
752The argument @var{time-value}, if given, specifies a time to format
753instead of the current time. The argument should be a cons cell
754containing two integers, or a list whose first two elements are
755integers. Thus, you can use times obtained from @code{current-time}
756(see below) and from @code{file-attributes} (@pxref{File Attributes}).
757
758@example
759@group
760(current-time-string)
761 @result{} "Wed Oct 14 22:21:05 1987"
762@end group
763@end example
764@end defun
765
766@c Emacs 19 feature
767@defun current-time
768This function returns the system's time value as a list of three
769integers: @code{(@var{high} @var{low} @var{microsec})}. The integers
770@var{high} and @var{low} combine to give the number of seconds since
7710:00 January 1, 1970, which is
772@ifinfo
773@var{high} * 2**16 + @var{low}.
774@end ifinfo
775@tex
776$high*-2^{16}+low$.
777@end tex
778
779The third element, @var{microsec}, gives the microseconds since the
780start of the current second (or 0 for systems that return time only on
781the resolution of a second).
782
783The first two elements can be compared with file time values such as you
784get with the function @code{file-attributes}. @xref{File Attributes}.
785@end defun
786
787@c Emacs 19 feature
788@defun current-time-zone &optional time-value
789This function returns a list describing the time zone that the user is
790in.
791
792The value has the form @code{(@var{offset} @var{name})}. Here
793@var{offset} is an integer giving the number of seconds ahead of UTC
794(east of Greenwich). A negative value means west of Greenwich. The
795second element, @var{name} is a string giving the name of the time
796zone. Both elements change when daylight savings time begins or ends;
797if the user has specified a time zone that does not use a seasonal time
798adjustment, then the value is constant through time.
799
800If the operating system doesn't supply all the information necessary to
801compute the value, both elements of the list are @code{nil}.
802
803The argument @var{time-value}, if given, specifies a time to analyze
804instead of the current time. The argument should be a cons cell
805containing two integers, or a list whose first two elements are
806integers. Thus, you can use times obtained from @code{current-time}
807(see below) and from @code{file-attributes} (@pxref{File Attributes}).
808@end defun
809
810@node Timers
811@section Timers
812
813You can set up a timer to call a function at a specified future time.
814
815@defun run-at-time time repeat function &rest args
816This function arranges to call @var{function} with arguments @var{args}
817at time @var{time}. The argument @var{function} is a function to call
818later, and @var{args} are the arguments to give it when it is called.
819The time @var{time} is specified as a string.
820
821Absolute times may be specified in a wide variety of formats; The form
822@samp{@var{hour}:@var{min}:@var{sec} @var{timezone}
823@var{month}/@var{day}/@var{year}}, where all fields are numbers, works;
824the format that @code{current-time-string} returns is also allowed.
825
826To specify a relative time, use numbers followed by units.
827For example:
828
829@table @samp
830@item 1 min
831denotes 1 minute from now.
832@item 1 min 5 sec
833denotes 65 seconds from now.
834@item 1 min 2 sec 3 hour 4 day 5 week 6 fortnight 7 month 8 year
835denotes exactly 103 months, 123 days, and 10862 seconds from now.
836@end table
837
838If @var{time} is an integer, that specifies a relative time measured in
839seconds.
840
841The argument @var{repeat} specifies how often to repeat the call. If
842@var{repeat} is @code{nil}, there are no repetitions; @var{function} is
843called just once, at @var{time}. If @var{repeat} is an integer, it
844specifies a repetition period measured in seconds.
845@end defun
846
847@defun cancel-timer timer
848Cancel the requested action for @var{timer}, which should be a value
849previously returned by @code{run-at-time}. This cancels the effect of
850that call to @code{run-at-time}; the arrival of the specified time will
851not cause anything special to happen.
852@end defun
853
854@node Terminal Input
855@section Terminal Input
856@cindex terminal input
857
858 This section describes functions and variables for recording or
859manipulating terminal input. See @ref{Display}, for related
860functions.
861
862@menu
863* Input Modes:: Options for how input is processed.
864* Translating Input:: Low level conversion of some characters or events
865 into others.
866* Recording Input:: Saving histories of recent or all input events.
867@end menu
868
869@node Input Modes
870@subsection Input Modes
871@cindex input modes
872@cindex terminal input modes
873
874@defun set-input-mode interrupt flow meta quit-char
875This function sets the mode for reading keyboard input. If
876@var{interrupt} is non-null, then Emacs uses input interrupts. If it is
877@code{nil}, then it uses @sc{cbreak} mode.
878
879If @var{flow} is non-@code{nil}, then Emacs uses @sc{xon/xoff} (@kbd{C-q},
880@kbd{C-s}) flow control for output to terminal. This has no effect except
881in @sc{cbreak} mode. @xref{Flow Control}.
882
883The default setting is system dependent. Some systems always use
884@sc{cbreak} mode regardless of what is specified.
885
886@c Emacs 19 feature
887The argument @var{meta} controls support for input character codes
888above 127. If @var{meta} is @code{t}, Emacs converts characters with
889the 8th bit set into Meta characters. If @var{meta} is @code{nil},
890Emacs disregards the 8th bit; this is necessary when the terminal uses
891it as a parity bit. If @var{meta} is neither @code{t} nor @code{nil},
892Emacs uses all 8 bits of input unchanged. This is good for terminals
893using European 8-bit character sets.
894
895@c Emacs 19 feature
896If @var{quit-char} is non-@code{nil}, it specifies the character to
897use for quitting. Normally this character is @kbd{C-g}.
898@xref{Quitting}.
899@end defun
900
901The @code{current-input-mode} function returns the input mode settings
902Emacs is currently using.
903
904@c Emacs 19 feature
905@defun current-input-mode
906This function returns current mode for reading keyboard input. It
907returns a list, corresponding to the arguments of @code{set-input-mode},
908of the form @code{(@var{interrupt} @var{flow} @var{meta} @var{quit})} in
909which:
910@table @var
911@item interrupt
912is non-@code{nil} when Emacs is using interrupt-driven input. If
913@code{nil}, Emacs is using @sc{cbreak} mode.
914@item flow
915is non-@code{nil} if Emacs uses @sc{xon/xoff} (@kbd{C-q}, @kbd{C-s})
916flow control for output to the terminal. This value has no effect
917unless @var{interrupt} is non-@code{nil}.
918@item meta
919is non-@code{t} if Emacs treats the eighth bit of input characters as
920the meta bit; @code{nil} means Emacs clears the eighth bit of every
921input character; any other value means Emacs uses all eight bits as the
922basic character code.
923@item quit
924is the character Emacs currently uses for quitting, usually @kbd{C-g}.
925@end table
926@end defun
927
928@defvar meta-flag
929This variable used to control whether to treat the eight bit in keyboard
930input characters as the @key{Meta} bit. @code{nil} meant no, and
931anything else meant yes. This variable existed in Emacs versions 18 and
932earlier but no longer exists in Emacs 19; use @code{set-input-mode}
933instead.
934@end defvar
935
936@node Translating Input
937@subsection Translating Input Events
938@cindex translating input events
939
940 This section describes features for translating input events into other
941input events before they become part of key sequences.
942
943@c Emacs 19 feature
944@defvar extra-keyboard-modifiers
945This variable lets Lisp programs ``press'' the modifier keys on the
946keyboard. The value is a bit mask:
947
948@table @asis
949@item 1
950The @key{SHIFT} key.
951@item 2
952The @key{LOCK} key.
953@item 4
954The @key{CTL} key.
955@item 8
956The @key{META} key.
957@end table
958
959Each time the user types a keyboard key, it is altered as if the
960modifier keys specified in the bit mask were held down.
961
962When you use X windows, the program can ``press'' any of the modifier
963keys in this way. Otherwise, only the @key{CTL} and @key{META} keys can
964be virtually pressed.
965@end defvar
966
967@defvar keyboard-translate-table
968This variable is the translate table for keyboard characters. It lets
969you reshuffle the keys on the keyboard without changing any command
970bindings. Its value must be a string or @code{nil}.
971
972If @code{keyboard-translate-table} is a string, then each character read
973from the keyboard is looked up in this string and the character in the
974string is used instead. If the string is of length @var{n}, character codes
975@var{n} and up are untranslated.
976
977In the example below, we set @code{keyboard-translate-table} to a
978string of 128 characters. Then we fill it in to swap the characters
979@kbd{C-s} and @kbd{C-\} and the characters @kbd{C-q} and @kbd{C-^}.
980Subsequently, typing @kbd{C-\} has all the usual effects of typing
981@kbd{C-s}, and vice versa. (@xref{Flow Control} for more information on
982this subject.)
983
984@cindex flow control example
985@example
986@group
987(defun evade-flow-control ()
988 "Replace C-s with C-\ and C-q with C-^."
989 (interactive)
990@end group
991@group
992 (let ((the-table (make-string 128 0)))
993 (let ((i 0))
994 (while (< i 128)
995 (aset the-table i i)
996 (setq i (1+ i))))
997@end group
998 ;; @r{Swap @kbd{C-s} and @kbd{C-\}.}
999 (aset the-table ?\034 ?\^s)
1000 (aset the-table ?\^s ?\034)
1001@group
1002 ;; @r{Swap @kbd{C-q} and @kbd{C-^}.}
1003 (aset the-table ?\036 ?\^q)
1004 (aset the-table ?\^q ?\036)
1005 (setq keyboard-translate-table the-table)))
1006@end group
1007@end example
1008
1009Note that this translation is the first thing that happens to a
1010character after it is read from the terminal. Record-keeping features
1011such as @code{recent-keys} and dribble files record the characters after
1012translation.
1013@end defvar
1014
1015@defun keyboard-translate from to
1016This function modifies @code{keyboard-translate-table} to translate
1017character code @var{from} into character code @var{to}. It creates
1018or enlarges the translate table if necessary.
1019@end defun
1020
1021@defvar function-key-map
1022This variable holds a keymap which describes the character sequences
1023sent by function keys on an ordinary character terminal. This keymap
1024uses the data structure as other keymaps, but is used differently: it
1025specifies translations to make while reading events.
1026
1027If @code{function-key-map} ``binds'' a key sequence @var{k} to a vector
1028@var{v}, then when @var{k} appears as a subsequence @emph{anywhere} in a
1029key sequence, it is replaced with the events in @var{v}.
1030
1031For example, VT100 terminals send @kbd{@key{ESC} O P} when the
1032keypad PF1 key is pressed. Therefore, we want Emacs to translate
1033that sequence of events into the single event @code{pf1}. We accomplish
1034this by ``binding'' @kbd{@key{ESC} O P} to @code{[pf1]} in
1035@code{function-key-map}, when using a VT100.
1036
1037Thus, typing @kbd{C-c @key{PF1}} sends the character sequence @kbd{C-c
1038@key{ESC} O P}; later the function @code{read-key-sequence} translates
1039this back into @kbd{C-c @key{PF1}}, which it returns as the vector
1040@code{[?\C-c pf1]}.
1041
1042Entries in @code{function-key-map} are ignored if they conflict with
1043bindings made in the minor mode, local, or global keymaps. The intent
1044is that the character sequences that function keys send should not have
1045command bindings in their own right.
1046
1047The value of @code{function-key-map} is usually set up automatically
1048according to the terminal's Terminfo or Termcap entry, but sometimes
1049those need help from terminal-specific Lisp files. Emacs comes with
1050terminal-specific files for many common terminals; their main purpose is
1051to make entries in @code{function-key-map} beyond those that can be
1052deduced from Termcap and Terminfo. @xref{Terminal-Specific}.
1053
1054Emacs versions 18 and earlier used totally different means of detecting
1055the character sequences that represent function keys.
1056@end defvar
1057
1058@defvar key-translation-map
1059This variable is another keymap used just like @code{function-key-map}
1060to translate input events into other events. It differs from
1061@code{function-key-map} in two ways:
1062
1063@itemize @bullet
1064@item
1065@code{key-translation-map} goes to work after @code{function-key-map} is
1066finished; it receives the results of translation by
1067@code{function-key-map}.
1068
1069@item
1070@code{key-translation-map} overrides actual key bindings.
1071@end itemize
1072
1073The intent of @code{key-translation-map} is for users to map one
1074character set to another, including ordinary characters normally bound
1075to @code{self-insert-command}.
1076@end defvar
1077
1078@cindex key translation function
1079You can use @code{function-key-map} or @code{key-translation-map} for
1080more than simple aliases, by using a function, instead of a key
1081sequence, as the ``translation'' of a key. Then this function is called
1082to compute the translation of that key.
1083
1084The key translation function receives one argument, which is the prompt
1085that was specified in @code{read-key-sequence}---or @code{nil} if the
1086key sequence is being read by the editor command loop. In most cases
1087you can ignore the prompt value.
1088
1089If the function reads input itself, it can have the effect of altering
1090the event that follows. For example, here's how to define @kbd{C-c h}
1091to turn the character that follows into a Hyper character:
1092
1093@example
1094(defun hyperify (prompt)
1095 (let ((e (read-event)))
1096 (vector (if (numberp e)
1097 (logior (lsh 1 20) e)
1098 (if (memq 'hyper (event-modifiers e))
1099 e
1100 (add-event-modifier "H-" e))))))
1101
1102(defun add-event-modifier (string e)
1103 (let ((symbol (if (symbolp e) e (car e))))
1104 (setq symbol (intern (concat string
1105 (symbol-name symbol))))
1106 (if (symbolp e)
1107 symbol
1108 (cons symbol (cdr e)))))
1109
1110(define-key function-key-map "\C-ch" 'hyperify)
1111@end example
1112
1113@pindex iso-transl
1114@cindex Latin-1 character set (input)
1115@cindex ISO Latin-1 characters (input)
1116The @file{iso-transl} library uses this feature to provide a way of
1117inputting non-ASCII Latin-1 characters.
1118
1119@node Recording Input
1120@subsection Recording Input
1121
1122@defun recent-keys
1123This function returns a vector containing the last 100 input events
1124from the keyboard or mouse. All input events are included, whether or
1125not they were used as parts of key sequences. Thus, you always get the
1126last 100 inputs, not counting keyboard macros. (Events from keyboard
1127macros are excluded because they are less interesting for debugging; it
1128should be enough to see the events which invoked the macros.)
1129@end defun
1130
1131@deffn Command open-dribble-file filename
1132@cindex dribble file
1133This function opens a @dfn{dribble file} named @var{filename}. When a
1134dribble file is open, each input event from the keyboard or mouse (but
1135not those from keyboard macros) is written in that file. A
1136non-character event is expressed using its printed representation
1137surrounded by @samp{<@dots{}>}.
1138
1139You close the dribble file by calling this function with an argument
1140of @code{nil}.
1141
1142This function is normally used to record the input necessary to
1143trigger an Emacs bug, for the sake of a bug report.
1144
1145@example
1146@group
1147(open-dribble-file "~/dribble")
1148 @result{} nil
1149@end group
1150@end example
1151@end deffn
1152
1153 See also the @code{open-termscript} function (@pxref{Terminal Output}).
1154
1155@node Terminal Output
1156@section Terminal Output
1157@cindex terminal output
1158
1159 The terminal output functions send output to the terminal or keep
1160track of output sent to the terminal. The variable @code{baud-rate}
1161tells you what Emacs thinks is the output speed of the terminal.
1162
1163@defvar baud-rate
1164This variable's value is the output speed of the terminal, as far as
1165Emacs knows. Setting this variable does not change the speed of actual
1166data transmission, but the value is used for calculations such as
1167padding. It also affects decisions about whether to scroll part of the
1168screen or repaint---even when using a window system, (We designed it
1169this way despite the fact that a window system has no true ``output
1170speed'', to give you a way to tune these decisions.)
1171
1172The value is measured in baud.
1173@end defvar
1174
1175 If you are running across a network, and different parts of the
1176network work at different baud rates, the value returned by Emacs may be
1177different from the value used by your local terminal. Some network
1178protocols communicate the local terminal speed to the remote machine, so
1179that Emacs and other programs can get the proper value, but others do
1180not. If Emacs has the wrong value, it makes decisions that are less
1181than optimal. To fix the problem, set @code{baud-rate}.
1182
1183@defun baud-rate
1184This function returns the value of the variable @code{baud-rate}. In
1185Emacs versions 18 and earlier, this was the only way to find out the
1186terminal speed.
1187@end defun
1188
1189@defun send-string-to-terminal string
1190This function sends @var{string} to the terminal without alteration.
1191Control characters in @var{string} have terminal-dependent effects.
1192
1193One use of this function is to define function keys on terminals that
1194have downloadable function key definitions. For example, this is how on
1195certain terminals to define function key 4 to move forward four
1196characters (by transmitting the characters @kbd{C-u C-f} to the
1197computer):
1198
1199@example
1200@group
1201(send-string-to-terminal "\eF4\^U\^F")
1202 @result{} nil
1203@end group
1204@end example
1205@end defun
1206
1207@deffn Command open-termscript filename
1208@cindex termscript file
1209This function is used to open a @dfn{termscript file} that will record
1210all the characters sent by Emacs to the terminal. It returns
1211@code{nil}. Termscript files are useful for investigating problems
1212where Emacs garbles the screen, problems that are due to incorrect
1213Termcap entries or to undesirable settings of terminal options more
1214often than to actual Emacs bugs. Once you are certain which characters
1215were actually output, you can determine reliably whether they correspond
1216to the Termcap specifications in use.
1217
1218See also @code{open-dribble-file} in @ref{Terminal Input}.
1219
1220@example
1221@group
1222(open-termscript "../junk/termscript")
1223 @result{} nil
1224@end group
1225@end example
1226@end deffn
1227
1228@node Special Keysyms
1229@section System-Specific X11 Keysyms
1230
1231To define system-specific X11 keysyms, set the variable
1232@code{system-key-alist}.
1233
1234@defvar system-key-alist
1235This variable's value should be an alist with one element for each
1236system-specific keysym. An element has this form: @code{(@var{code}
1237. @var{symbol})}, where @var{code} is the numeric keysym code (not
1238including the ``vendor specific'' bit, 1 << 28), and @var{symbol} is the
1239name for the function key.
1240
1241For example @code{(168 . mute-acute)} defines a system-specific key used
1242by HP X servers whose numeric code is (1 << 28) + 168.
1243
1244It is not a problem if the alist defines keysyms for other X servers, as
1245long as they don't conflict with the ones used by the X server actually
1246in use.
1247@end defvar
1248
1249@node Flow Control
1250@section Flow Control
1251@cindex flow control characters
1252
1253 This section attempts to answer the question ``Why does Emacs choose
1254to use flow-control characters in its command character set?'' For a
1255second view on this issue, read the comments on flow control in the
1256@file{emacs/INSTALL} file from the distribution; for help with Termcap
1257entries and DEC terminal concentrators, see @file{emacs/etc/TERMS}.
1258
1259@cindex @kbd{C-s}
1260@cindex @kbd{C-q}
1261 At one time, most terminals did not need flow control, and none used
1262@code{C-s} and @kbd{C-q} for flow control. Therefore, the choice of
1263@kbd{C-s} and @kbd{C-q} as command characters was uncontroversial.
1264Emacs, for economy of keystrokes and portability, used nearly all the
1265@sc{ASCII} control characters, with mnemonic meanings when possible;
1266thus, @kbd{C-s} for search and @kbd{C-q} for quote.
1267
1268 Later, some terminals were introduced which required these characters
1269for flow control. They were not very good terminals for full-screen
1270editing, so Emacs maintainers did not pay attention. In later years,
1271flow control with @kbd{C-s} and @kbd{C-q} became widespread among
1272terminals, but by this time it was usually an option. And the majority
1273of users, who can turn flow control off, were unwilling to switch to
1274less mnemonic key bindings for the sake of flow control.
1275
1276 So which usage is ``right'', Emacs's or that of some terminal and
1277concentrator manufacturers? This question has no simple answer.
1278
1279 One reason why we are reluctant to cater to the problems caused by
1280@kbd{C-s} and @kbd{C-q} is that they are gratuitous. There are other
1281techniques (albeit less common in practice) for flow control that
1282preserve transparency of the character stream. Note also that their use
1283for flow control is not an official standard. Interestingly, on the
1284model 33 teletype with a paper tape punch (which is very old), @kbd{C-s}
1285and @kbd{C-q} were sent by the computer to turn the punch on and off!
1286
1287 GNU Emacs version 19 provides a convenient way of enabling flow
1288control if you want it: call the function @code{enable-flow-control}.
1289
1290@defun enable-flow-control
1291This function enables use of @kbd{C-s} and @kbd{C-q} for output flow
1292control, and provides the characters @kbd{C-\} and @kbd{C-^} as aliases
1293for them using @code{keyboard-translate-table} (@pxref{Translating Input}).
1294@end defun
1295
1296You can use the function @code{enable-flow-control-on} in your
1297@file{.emacs} file to enable flow control automatically on certain
1298terminal types.
1299
1300@defun enable-flow-control-on &rest termtypes
1301This function enables flow control, and the aliases @kbd{C-\} and @kbd{C-^},
1302if the terminal type is one of @var{termtypes}. For example:
1303
1304@smallexample
1305(enable-flow-control-on "vt200" "vt300" "vt101" "vt131")
1306@end smallexample
1307@end defun
1308
1309 Here is how @code{enable-flow-control} does its job:
1310
1311@enumerate
1312@item
1313@cindex @sc{cbreak}
1314It sets @sc{cbreak} mode for terminal input, and tells the operating
1315system to handle flow control, with @code{(set-input-mode nil t)}.
1316
1317@item
1318It sets up @code{keyboard-translate-table} to translate @kbd{C-\} and
1319@kbd{C-^} into @kbd{C-s} and @kbd{C-q} were typed. Except at its very
1320lowest level, Emacs never knows that the characters typed were anything
1321but @kbd{C-s} and @kbd{C-q}, so you can in effect type them as @kbd{C-\}
1322and @kbd{C-^} even when they are input for other commands.
1323@xref{Translating Input}.
1324
1325If the terminal is the source of the flow control characters, then once
1326you enable kernel flow control handling, you probably can make do with
1327less padding than normal for that terminal. You can reduce the amount
1328of padding by customizing the Termcap entry. You can also reduce it by
1329setting @code{baud-rate} to a smaller value so that Emacs uses a smaller
1330speed when calculating the padding needed. @xref{Terminal Output}.
1331
1332@node Batch Mode
1333@section Batch Mode
1334@cindex batch mode
1335@cindex noninteractive use
1336
1337 The command line option @samp{-batch} causes Emacs to run
1338noninteractively. In this mode, Emacs does not read commands from the
1339terminal, it does not alter the terminal modes, and it does not expect
1340to be outputting to an erasable screen. The idea is that you specify
1341Lisp programs to run; when they are finished, Emacs should exit. The
1342way to specify the programs to run is with @samp{-l @var{file}}, which
1343loads the library named @var{file}, and @samp{-f @var{function}}, which
1344calls @var{function} with no arguments.
1345
1346 Any Lisp program output that would normally go to the echo area,
1347either using @code{message} or using @code{prin1}, etc., with @code{t}
1348as the stream, goes instead to Emacs's standard output descriptor when
1349in batch mode. Thus, Emacs behaves much like a noninteractive
1350application program. (The echo area output that Emacs itself normally
1351generates, such as command echoing, is suppressed entirely.)
1352
1353@defvar noninteractive
1354This variable is non-@code{nil} when Emacs is running in batch mode.
1355@end defvar
diff --git a/lispref/processes.texi b/lispref/processes.texi
new file mode 100644
index 00000000000..d4479bebeae
--- /dev/null
+++ b/lispref/processes.texi
@@ -0,0 +1,1139 @@
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/processes
6@node Processes, System Interface, Abbrevs, Top
7@chapter Processes
8@cindex child process
9@cindex parent process
10@cindex subprocess
11@cindex process
12
13 In the terminology of operating systems, a @dfn{process} is a space in
14which a program can execute. Emacs runs in a process. Emacs Lisp
15programs can invoke other programs in processes of their own. These are
16called @dfn{subprocesses} or @dfn{child processes} of the Emacs process,
17which is their @dfn{parent process}.
18
19 A subprocess of Emacs may be @dfn{synchronous} or @dfn{asynchronous},
20depending on how it is created. When you create a synchronous
21subprocess, the Lisp program waits for the subprocess to terminate
22before continuing execution. When you create an asynchronous
23subprocess, it can run in parallel with the Lisp program. This kind of
24subprocess is represented within Emacs by a Lisp object which is also
25called a ``process''. Lisp programs can use this object to communicate
26with the subprocess or to control it. For example, you can send
27signals, obtain status information, receive output from the process, or
28send input to it.
29
30@defun processp object
31This function returns @code{t} if @var{object} is a process,
32@code{nil} otherwise.
33@end defun
34
35@menu
36* Subprocess Creation:: Functions that start subprocesses.
37* Synchronous Processes:: Details of using synchronous subprocesses.
38* Asynchronous Processes:: Starting up an asynchronous subprocess.
39* Deleting Processes:: Eliminating an asynchronous subprocess.
40* Process Information:: Accessing run-status and other attributes.
41* Input to Processes:: Sending input to an asynchronous subprocess.
42* Signals to Processes:: Stopping, continuing or interrupting
43 an asynchronous subprocess.
44* Output from Processes:: Collecting output from an asynchronous subprocess.
45* Sentinels:: Sentinels run when process run-status changes.
46* Transaction Queues:: Transaction-based communication with subprocesses.
47* TCP:: Opening network connections.
48@end menu
49
50@node Subprocess Creation
51@section Functions that Create Subprocesses
52
53 There are three functions that create a new subprocess in which to run
54a program. One of them, @code{start-process}, creates an asynchronous
55process and returns a process object (@pxref{Asynchronous Processes}).
56The other two, @code{call-process} and @code{call-process-region},
57create a synchronous process and do not return a process object
58(@pxref{Synchronous Processes}).
59
60 Synchronous and asynchronous processes are explained in following
61sections. Since the three functions are all called in a similar
62fashion, their common arguments are described here.
63
64@cindex execute program
65@cindex @code{PATH} environment variable
66@cindex @code{HOME} environment variable
67 In all cases, the function's @var{program} argument specifies the
68program to be run. An error is signaled if the file is not found or
69cannot be executed. If the file name is relative, the variable
70@code{exec-path} contains a list of directories to search. Emacs
71initializes @code{exec-path} when it starts up, based on the value of
72the environment variable @code{PATH}. The standard file name
73constructs, @samp{~}, @samp{.}, and @samp{..}, are interpreted as usual
74in @code{exec-path}, but environment variable substitutions
75(@samp{$HOME}, etc.) are not recognized; use
76@code{substitute-in-file-name} to perform them (@pxref{File Name
77Expansion}).
78
79 Each of the subprocess-creating functions has a @var{buffer-or-name}
80argument which specifies where the standard output from the program will
81go. If @var{buffer-or-name} is @code{nil}, that says to discard the
82output unless a filter function handles it. (@xref{Filter Functions},
83and @ref{Streams}.) Normally, you should avoid having multiple
84processes send output to the same buffer because their output would be
85intermixed randomly.
86
87@cindex program arguments
88 All three of the subprocess-creating functions have a @code{&rest}
89argument, @var{args}. The @var{args} must all be strings, and they are
90supplied to @var{program} as separate command line arguments. Wildcard
91characters and other shell constructs are not allowed in these strings,
92since they are passed directly to the specified program.
93
94 @strong{Please note:} the argument @var{program} contains only the
95name of the program; it may not contain any command-line arguments. You
96must use @var{args} to provide those.
97
98 The subprocess gets its current directory from the value of
99@code{default-directory} (@pxref{File Name Expansion}).
100
101@cindex environment variables, subprocesses
102 The subprocess inherits its environment from Emacs; but you can
103specify overrides for it with @code{process-environment}. @xref{System
104Environment}.
105
106@defvar exec-directory
107@pindex wakeup
108The value of this variable is the name of a directory (a string) that
109contains programs that come with GNU Emacs, that are intended for Emacs
110to invoke. The program @code{wakeup} is an example of such a program;
111the @code{display-time} command uses it to get a reminder once per
112minute.
113@end defvar
114
115@defopt exec-path
116The value of this variable is a list of directories to search for
117programs to run in subprocesses. Each element is either the name of a
118directory (i.e., a string), or @code{nil}, which stands for the default
119directory (which is the value of @code{default-directory}).
120@cindex program directories
121
122The value of @code{exec-path} is used by @code{call-process} and
123@code{start-process} when the @var{program} argument is not an absolute
124file name.
125@end defopt
126
127@node Synchronous Processes
128@section Creating a Synchronous Process
129@cindex synchronous subprocess
130
131 After a @dfn{synchronous process} is created, Emacs waits for the
132process to terminate before continuing. Starting Dired is an example of
133this: it runs @code{ls} in a synchronous process, then modifies the
134output slightly. Because the process is synchronous, the entire
135directory listing arrives in the buffer before Emacs tries to do
136anything with it.
137
138 While Emacs waits for the synchronous subprocess to terminate, the
139user can quit by typing @kbd{C-g}. The first @kbd{C-g} tries to kill
140the subprocess with a @code{SIGINT} signal; but it waits until the
141subprocess actually terminates before quitting. If during that time the
142user types another @kbd{C-g}, that kills the subprocess instantly with
143@code{SIGKILL} and quits immediately. @xref{Quitting}.
144
145 The synchronous subprocess functions returned @code{nil} in version
14618. In version 19, they return an indication of how the process
147terminated.
148
149@defun call-process program &optional infile buffer-or-name display &rest args
150This function calls @var{program} in a separate process and waits for
151it to finish.
152
153The standard input for the process comes from file @var{infile} if
154@var{infile} is not @code{nil} and from @file{/dev/null} otherwise. The
155process output gets inserted in buffer @var{buffer-or-name} before point,
156if that argument names a buffer. If @var{buffer-or-name} is @code{t},
157output is sent to the current buffer; if @var{buffer-or-name} is
158@code{nil}, output is discarded.
159
160If @var{buffer-or-name} is the integer 0, @code{call-process} returns
161@code{nil} immediately and discards any output. In this case, the
162process is not truly synchronous, since it can run in parallel with
163Emacs; but you can think of it as synchronous in that Emacs is
164essentially finished with the subprocess as soon as this function
165returns.
166
167If @var{display} is non-@code{nil}, then @code{call-process} redisplays
168the buffer as output is inserted. Otherwise the function does no
169redisplay, and the results become visible on the screen only when Emacs
170redisplays that buffer in the normal course of events.
171
172The remaining arguments, @var{args}, are strings that specify command
173line arguments for the program.
174
175The value returned by @code{call-process} (unless you told it not to
176wait) indicates the reason for process termination. A number gives the
177exit status of the subprocess; 0 means success, and any other value
178means failure. If the process terminated with a signal,
179@code{call-process} returns a string describing the signal.
180
181In the examples below, the buffer @samp{foo} is current.
182
183@smallexample
184@group
185(call-process "pwd" nil t)
186 @result{} nil
187
188---------- Buffer: foo ----------
189/usr/user/lewis/manual
190---------- Buffer: foo ----------
191@end group
192
193@group
194(call-process "grep" nil "bar" nil "lewis" "/etc/passwd")
195 @result{} nil
196
197---------- Buffer: bar ----------
198lewis:5LTsHm66CSWKg:398:21:Bil Lewis:/user/lewis:/bin/csh
199
200---------- Buffer: bar ----------
201@end group
202@end smallexample
203
204The @code{insert-directory} function contains a good example of the use
205of @code{call-process}:
206
207@smallexample
208@group
209(call-process insert-directory-program nil t nil switches
210 (if full-directory-p
211 (concat (file-name-as-directory file) ".")
212 file))
213@end group
214@end smallexample
215@end defun
216
217@defun call-process-region start end program &optional delete buffer-or-name display &rest args
218This function sends the text between @var{start} to @var{end} as
219standard input to a process running @var{program}. It deletes the text
220sent if @var{delete} is non-@code{nil}; this is useful when @var{buffer}
221is @code{t}, to insert the output in the current buffer.
222
223The arguments @var{buffer-or-name} and @var{display} control what to do
224with the output from the subprocess, and whether to update the display
225as it comes in. For details, see the description of
226@code{call-process}, above. If @var{buffer-or-name} is the integer 0,
227@code{call-process-region} discards the output and returns @code{nil}
228immediately, without waiting for the subprocess to finish.
229
230The remaining arguments, @var{args}, are strings that specify command
231line arguments for the program.
232
233The return value of @code{call-process-region} is just like that of
234@code{call-process}: @code{nil} if you told it to return without
235waiting; otherwise, a number or string which indicates how the
236subprocess terminated.
237
238In the following example, we use @code{call-process-region} to run the
239@code{cat} utility, with standard input being the first five characters
240in buffer @samp{foo} (the word @samp{input}). @code{cat} copies its
241standard input into its standard output. Since the argument
242@var{buffer-or-name} is @code{t}, this output is inserted in the current
243buffer.
244
245@smallexample
246@group
247---------- Buffer: foo ----------
248input@point{}
249---------- Buffer: foo ----------
250@end group
251
252@group
253(call-process-region 1 6 "cat" nil t)
254 @result{} nil
255
256---------- Buffer: foo ----------
257inputinput@point{}
258---------- Buffer: foo ----------
259@end group
260@end smallexample
261
262 The @code{shell-command-on-region} command uses
263@code{call-process-region} like this:
264
265@smallexample
266@group
267(call-process-region
268 start end
269 shell-file-name ; @r{Name of program.}
270 nil ; @r{Do not delete region.}
271 buffer ; @r{Send output to @code{buffer}.}
272 nil ; @r{No redisplay during output.}
273 "-c" command) ; @r{Arguments for the shell.}
274@end group
275@end smallexample
276@end defun
277
278@node Asynchronous Processes
279@section Creating an Asynchronous Process
280@cindex asynchronous subprocess
281
282 After an @dfn{asynchronous process} is created, Emacs and the Lisp
283program both continue running immediately. The process may thereafter
284run in parallel with Emacs, and the two may communicate with each other
285using the functions described in following sections. Here we describe
286how to create an asynchronous process with @code{start-process}.
287
288@defun start-process name buffer-or-name program &rest args
289This function creates a new asynchronous subprocess and starts the
290program @var{program} running in it. It returns a process object that
291stands for the new subprocess in Lisp. The argument @var{name}
292specifies the name for the process object; if a process with this name
293already exists, then @var{name} is modified (by adding @samp{<1>}, etc.)
294to be unique. The buffer @var{buffer-or-name} is the buffer to
295associate with the process.
296
297The remaining arguments, @var{args}, are strings that specify command
298line arguments for the program.
299
300In the example below, the first process is started and runs (rather,
301sleeps) for 100 seconds. Meanwhile, the second process is started, and
302given the name @samp{my-process<1>} for the sake of uniqueness. It
303inserts the directory listing at the end of the buffer @samp{foo},
304before the first process finishes. Then it finishes, and a message to
305that effect is inserted in the buffer. Much later, the first process
306finishes, and another message is inserted in the buffer for it.
307
308@smallexample
309@group
310(start-process "my-process" "foo" "sleep" "100")
311 @result{} #<process my-process>
312@end group
313
314@group
315(start-process "my-process" "foo" "ls" "-l" "/user/lewis/bin")
316 @result{} #<process my-process<1>>
317
318---------- Buffer: foo ----------
319total 2
320lrwxrwxrwx 1 lewis 14 Jul 22 10:12 gnuemacs --> /emacs
321-rwxrwxrwx 1 lewis 19 Jul 30 21:02 lemon
322
323Process my-process<1> finished
324
325Process my-process finished
326---------- Buffer: foo ----------
327@end group
328@end smallexample
329@end defun
330
331@defun start-process-shell-command name buffer-or-name command &rest command-args
332This function is like @code{start-process} except that it uses a shell
333to execute the specified command. The argument @var{command} is a shell
334command name, and @var{command-args} are the arguments for the shell
335command.
336@end defun
337
338@defvar process-connection-type
339@cindex pipes
340@cindex @sc{pty}s
341This variable controls the type of device used to communicate with
342asynchronous subprocesses. If it is @code{nil}, then pipes are used.
343If it is @code{t}, then @sc{pty}s are used (or pipes if @sc{pty}s are
344not supported).
345
346@sc{pty}s are usually preferable for processes visible to the user, as
347in Shell mode, because they allow job control (@kbd{C-c}, @kbd{C-z},
348etc.) to work between the process and its children whereas pipes do not.
349For subprocesses used for internal purposes by programs, it is often
350better to use a pipe, because they are more efficient. In addition, the
351total number of @sc{pty}s is limited on many systems and it is good not
352to waste them.
353
354The value @code{process-connection-type} is used when
355@code{start-process} is called. So you can specify how to communicate
356with one subprocess by binding the variable around the call to
357@code{start-process}.
358
359@smallexample
360@group
361(let ((process-connection-type nil)) ; @r{Use a pipe.}
362 (start-process @dots{}))
363@end group
364@end smallexample
365@end defvar
366
367@node Deleting Processes
368@section Deleting Processes
369@cindex deleting processes
370
371 @dfn{Deleting a process} disconnects Emacs immediately from the
372subprocess, and removes it from the list of active processes. It sends
373a signal to the subprocess to make the subprocess terminate, but this is
374not guaranteed to happen immediately. The process object itself
375continues to exist as long as other Lisp objects point to it.
376
377 You can delete a process explicitly at any time. Processes are
378deleted automatically after they terminate, but not necessarily right
379away. If you delete a terminated process explicitly before it is
380deleted automatically, no harm results.
381
382@defvar delete-exited-processes
383This variable controls automatic deletion of processes that have
384terminated (due to calling @code{exit} or to a signal). If it is
385@code{nil}, then they continue to exist until the user runs
386@code{list-processes}. Otherwise, they are deleted immediately after
387they exit.
388@end defvar
389
390@defun delete-process name
391This function deletes the process associated with @var{name}, killing it
392with a @code{SIGHUP} signal. The argument @var{name} may be a process,
393the name of a process, a buffer, or the name of a buffer.
394
395@smallexample
396@group
397(delete-process "*shell*")
398 @result{} nil
399@end group
400@end smallexample
401@end defun
402
403@defun process-kill-without-query process
404This function declares that Emacs need not query the user if
405@var{process} is still running when Emacs is exited. The process will
406be deleted silently. The value is @code{t}.
407
408@smallexample
409@group
410(process-kill-without-query (get-process "shell"))
411 @result{} t
412@end group
413@end smallexample
414@end defun
415
416@node Process Information
417@section Process Information
418
419 Several functions return information about processes.
420@code{list-processes} is provided for interactive use.
421
422@deffn Command list-processes
423This command displays a listing of all living processes. In addition,
424it finally deletes any process whose status was @samp{Exited} or
425@samp{Signaled}. It returns @code{nil}.
426@end deffn
427
428@defun process-list
429This function returns a list of all processes that have not been deleted.
430
431@smallexample
432@group
433(process-list)
434 @result{} (#<process display-time> #<process shell>)
435@end group
436@end smallexample
437@end defun
438
439@defun get-process name
440This function returns the process named @var{name}, or @code{nil} if
441there is none. An error is signaled if @var{name} is not a string.
442
443@smallexample
444@group
445(get-process "shell")
446 @result{} #<process shell>
447@end group
448@end smallexample
449@end defun
450
451@defun process-command process
452This function returns the command that was executed to start
453@var{process}. This is a list of strings, the first string being the
454program executed and the rest of the strings being the arguments that
455were given to the program.
456
457@smallexample
458@group
459(process-command (get-process "shell"))
460 @result{} ("/bin/csh" "-i")
461@end group
462@end smallexample
463@end defun
464
465@defun process-id process
466This function returns the @sc{pid} of @var{process}. This is an
467integer which distinguishes the process @var{process} from all other
468processes running on the same computer at the current time. The
469@sc{pid} of a process is chosen by the operating system kernel when the
470process is started and remains constant as long as the process exists.
471@end defun
472
473@defun process-name process
474This function returns the name of @var{process}.
475@end defun
476
477@defun process-status process-name
478This function returns the status of @var{process-name} as a symbol.
479The argument @var{process-name} must be a process, a buffer, a
480process name (string) or a buffer name (string).
481
482The possible values for an actual subprocess are:
483
484@table @code
485@item run
486for a process that is running.
487@item stop
488for a process that is stopped but continuable.
489@item exit
490for a process that has exited.
491@item signal
492for a process that has received a fatal signal.
493@item open
494for a network connection that is open.
495@item closed
496for a network connection that is closed. Once a connection
497is closed, you cannot reopen it, though you might be able to open
498a new connection to the same place.
499@item nil
500if @var{process-name} is not the name of an existing process.
501@end table
502
503@smallexample
504@group
505(process-status "shell")
506 @result{} run
507@end group
508@group
509(process-status (get-buffer "*shell*"))
510 @result{} run
511@end group
512@group
513x
514 @result{} #<process xx<1>>
515(process-status x)
516 @result{} exit
517@end group
518@end smallexample
519
520For a network connection, @code{process-status} returns one of the symbols
521@code{open} or @code{closed}. The latter means that the other side
522closed the connection, or Emacs did @code{delete-process}.
523
524In earlier Emacs versions (prior to version 19), the status of a network
525connection was @code{run} if open, and @code{exit} if closed.
526@end defun
527
528@defun process-exit-status process
529This function returns the exit status of @var{process} or the signal
530number that killed it. (Use the result of @code{process-status} to
531determine which of those it is.) If @var{process} has not yet
532terminated, the value is 0.
533@end defun
534
535@node Input to Processes
536@section Sending Input to Processes
537@cindex process input
538
539 Asynchronous subprocesses receive input when it is sent to them by
540Emacs, which is done with the functions in this section. You must
541specify the process to send input to, and the input data to send. The
542data appears on the ``standard input'' of the subprocess.
543
544 Some operating systems have limited space for buffered input in a
545@sc{pty}. On these systems, Emacs sends an @sc{eof} periodically amidst
546the other characters, to force them through. For most programs,
547these @sc{eof}s do no harm.
548
549@defun process-send-string process-name string
550This function sends @var{process-name} the contents of @var{string} as
551standard input. The argument @var{process-name} must be a process or
552the name of a process. If it is @code{nil}, the current buffer's
553process is used.
554
555 The function returns @code{nil}.
556
557@smallexample
558@group
559(process-send-string "shell<1>" "ls\n")
560 @result{} nil
561@end group
562
563
564@group
565---------- Buffer: *shell* ----------
566...
567introduction.texi syntax-tables.texi~
568introduction.texi~ text.texi
569introduction.txt text.texi~
570...
571---------- Buffer: *shell* ----------
572@end group
573@end smallexample
574@end defun
575
576@deffn Command process-send-region process-name start end
577This function sends the text in the region defined by @var{start} and
578@var{end} as standard input to @var{process-name}, which is a process or
579a process name. (If it is @code{nil}, the current buffer's process is
580used.)
581
582An error is signaled unless both @var{start} and @var{end} are
583integers or markers that indicate positions in the current buffer. (It
584is unimportant which number is larger.)
585@end deffn
586
587@defun process-send-eof &optional process-name
588 This function makes @var{process-name} see an end-of-file in its
589input. The @sc{eof} comes after any text already sent to it.
590
591 If @var{process-name} is not supplied, or if it is @code{nil}, then
592this function sends the @sc{eof} to the current buffer's process. An
593error is signaled if the current buffer has no process.
594
595 The function returns @var{process-name}.
596
597@smallexample
598@group
599(process-send-eof "shell")
600 @result{} "shell"
601@end group
602@end smallexample
603@end defun
604
605@node Signals to Processes
606@section Sending Signals to Processes
607@cindex process signals
608@cindex sending signals
609@cindex signals
610
611 @dfn{Sending a signal} to a subprocess is a way of interrupting its
612activities. There are several different signals, each with its own
613meaning. The set of signals and their names is defined by the operating
614system. For example, the signal @code{SIGINT} means that the user has
615typed @kbd{C-c}, or that some analogous thing has happened.
616
617 Each signal has a standard effect on the subprocess. Most signals
618kill the subprocess, but some stop or resume execution instead. Most
619signals can optionally be handled by programs; if the program handles
620the signal, then we can say nothing in general about its effects.
621
622 You can send signals explicitly by calling the functions in this
623section. Emacs also sends signals automatically at certain times:
624killing a buffer sends a @code{SIGHUP} signal to all its associated
625processes; killing Emacs sends a @code{SIGHUP} signal to all remaining
626processes. (@code{SIGHUP} is a signal that usually indicates that the
627user hung up the phone.)
628
629 Each of the signal-sending functions takes two optional arguments:
630@var{process-name} and @var{current-group}.
631
632 The argument @var{process-name} must be either a process, the name of
633one, or @code{nil}. If it is @code{nil}, the process defaults to the
634process associated with the current buffer. An error is signaled if
635@var{process-name} does not identify a process.
636
637 The argument @var{current-group} is a flag that makes a difference
638when you are running a job-control shell as an Emacs subprocess. If it
639is non-@code{nil}, then the signal is sent to the current process-group
640of the terminal which Emacs uses to communicate with the subprocess. If
641the process is a job-control shell, this means the shell's current
642subjob. If it is @code{nil}, the signal is sent to the process group of
643the immediate subprocess of Emacs. If the subprocess is a job-control
644shell, this is the shell itself.
645
646 The flag @var{current-group} has no effect when a pipe is used to
647communicate with the subprocess, because the operating system does not
648support the distinction in the case of pipes. For the same reason,
649job-control shells won't work when a pipe is used. See
650@code{process-connection-type} in @ref{Asynchronous Processes}.
651
652@defun interrupt-process &optional process-name current-group
653This function interrupts the process @var{process-name} by sending the
654signal @code{SIGINT}. Outside of Emacs, typing the ``interrupt
655character'' (normally @kbd{C-c} on some systems, and @code{DEL} on
656others) sends this signal. When the argument @var{current-group} is
657non-@code{nil}, you can think of this function as ``typing @kbd{C-c}''
658on the terminal by which Emacs talks to the subprocess.
659@end defun
660
661@defun kill-process &optional process-name current-group
662This function kills the process @var{process-name} by sending the
663signal @code{SIGKILL}. This signal kills the subprocess immediately,
664and cannot be handled by the subprocess.
665@end defun
666
667@defun quit-process &optional process-name current-group
668This function sends the signal @code{SIGQUIT} to the process
669@var{process-name}. This signal is the one sent by the ``quit
670character'' (usually @kbd{C-b} or @kbd{C-\}) when you are not inside
671Emacs.
672@end defun
673
674@defun stop-process &optional process-name current-group
675This function stops the process @var{process-name} by sending the
676signal @code{SIGTSTP}. Use @code{continue-process} to resume its
677execution.
678
679On systems with job control, the ``stop character'' (usually @kbd{C-z})
680sends this signal (outside of Emacs). When @var{current-group} is
681non-@code{nil}, you can think of this function as ``typing @kbd{C-z}''
682on the terminal Emacs uses to communicate with the subprocess.
683@end defun
684
685@defun continue-process &optional process-name current-group
686This function resumes execution of the process @var{process} by sending
687it the signal @code{SIGCONT}. This presumes that @var{process-name} was
688stopped previously.
689@end defun
690
691@c Emacs 19 feature
692@defun signal-process pid signal
693This function sends a signal to process @var{pid}, which need not be
694a child of Emacs. The argument @var{signal} specifies which signal
695to send; it should be an integer.
696@end defun
697
698@node Output from Processes
699@section Receiving Output from Processes
700@cindex process output
701@cindex output from processes
702
703 There are two ways to receive the output that a subprocess writes to
704its standard output stream. The output can be inserted in a buffer,
705which is called the associated buffer of the process, or a function
706called the @dfn{filter function} can be called to act on the output.
707
708@menu
709* Process Buffers:: If no filter, output is put in a buffer.
710* Filter Functions:: Filter functions accept output from the process.
711* Accepting Output:: Explicitly permitting subprocess output.
712 Waiting for subprocess output.
713@end menu
714
715@node Process Buffers
716@subsection Process Buffers
717
718 A process can (and usually does) have an @dfn{associated buffer},
719which is an ordinary Emacs buffer that is used for two purposes: storing
720the output from the process, and deciding when to kill the process. You
721can also use the buffer to identify a process to operate on, since in
722normal practice only one process is associated with any given buffer.
723Many applications of processes also use the buffer for editing input to
724be sent to the process, but this is not built into Emacs Lisp.
725
726 Unless the process has a filter function (@pxref{Filter Functions}),
727its output is inserted in the associated buffer. The position to insert
728the output is determined by the @code{process-mark} (@pxref{Process
729Information}), which is then updated to point to the end of the text
730just inserted. Usually, but not always, the @code{process-mark} is at
731the end of the buffer. If the process has no buffer and no filter
732function, its output is discarded.
733
734@defun process-buffer process
735This function returns the associated buffer of the process
736@var{process}.
737
738@smallexample
739@group
740(process-buffer (get-process "shell"))
741 @result{} #<buffer *shell*>
742@end group
743@end smallexample
744@end defun
745
746@defun process-mark process
747This function returns the process marker for @var{process}, which is the
748marker that says where to insert output from the process.
749
750If @var{process} does not have a buffer, @code{process-mark} returns a
751marker that points nowhere.
752
753Insertion of process output in a buffer uses this marker to decide where
754to insert, and updates it to point after the inserted text. That is why
755successive batches of output are inserted consecutively.
756
757Filter functions normally should use this marker in the same fashion
758as is done by direct insertion of output in the buffer. A good
759example of a filter function that uses @code{process-mark} is found at
760the end of the following section.
761
762When the user is expected to enter input in the process buffer for
763transmission to the process, the process marker is useful for
764distinguishing the new input from previous output.
765@end defun
766
767@defun set-process-buffer process buffer
768This function sets the buffer associated with @var{process} to
769@var{buffer}. If @var{buffer} is @code{nil}, the process becomes
770associated with no buffer.
771@end defun
772
773@defun get-buffer-process buffer-or-name
774This function returns the process associated with @var{buffer-or-name}.
775If there are several processes associated with it, then one is chosen.
776(Presently, the one chosen is the one most recently created.) It is
777usually a bad idea to have more than one process associated with the
778same buffer.
779
780@smallexample
781@group
782(get-buffer-process "*shell*")
783 @result{} #<process shell>
784@end group
785@end smallexample
786
787Killing the process's buffer deletes the process, which kills the
788subprocess with a @code{SIGHUP} signal (@pxref{Signals to Processes}).
789@end defun
790
791@node Filter Functions
792@subsection Process Filter Functions
793@cindex filter function
794@cindex process filter
795
796 A process @dfn{filter function} is a function that receives the
797standard output from the associated process. If a process has a filter,
798then @emph{all} output from that process, that would otherwise have been
799in a buffer, is passed to the filter. The process buffer is used
800directly for output from the process only when there is no filter.
801
802 A filter function must accept two arguments: the associated process and
803a string, which is the output. The function is then free to do whatever it
804chooses with the output.
805
806 A filter function runs only while Emacs is waiting (e.g., for terminal
807input, or for time to elapse, or for process output). This avoids the
808timing errors that could result from running filters at random places in
809the middle of other Lisp programs. You may explicitly cause Emacs to
810wait, so that filter functions will run, by calling @code{sit-for},
811@code{sleep-for} or @code{accept-process-output} (@pxref{Accepting
812Output}). Emacs is also waiting when the command loop is reading input.
813
814 Quitting is normally inhibited within a filter function---otherwise,
815the effect of typing @kbd{C-g} at command level or to quit a user
816command would be unpredictable. If you want to permit quitting inside a
817filter function, bind @code{inhibit-quit} to @code{nil}.
818@xref{Quitting}.
819
820 Many filter functions sometimes or always insert the text in the
821process's buffer, mimicking the actions of Emacs when there is no
822filter. Such filter functions need to use @code{set-buffer} in order to
823be sure to insert in that buffer. To avoid setting the current buffer
824semipermanently, these filter functions must use @code{unwind-protect}
825to make sure to restore the previous current buffer. They should also
826update the process marker, and in some cases update the value of point.
827Here is how to do these things:
828
829@smallexample
830@group
831(defun ordinary-insertion-filter (proc string)
832 (let ((old-buffer (current-buffer)))
833 (unwind-protect
834 (let (moving)
835 (set-buffer (process-buffer proc))
836 (setq moving (= (point) (process-mark proc)))
837@end group
838@group
839 (save-excursion
840 ;; @r{Insert the text, moving the process-marker.}
841 (goto-char (process-mark proc))
842 (insert string)
843 (set-marker (process-mark proc) (point)))
844 (if moving (goto-char (process-mark proc))))
845 (set-buffer old-buffer))))
846@end group
847@end smallexample
848
849@noindent
850The reason to use an explicit @code{unwind-protect} rather than letting
851@code{save-excursion} restore the current buffer is so as to preserve
852the change in point made by @code{goto-char}.
853
854 To make the filter force the process buffer to be visible whenever new
855text arrives, insert the following line just before the
856@code{unwind-protect}:
857
858@smallexample
859(display-buffer (process-buffer proc))
860@end smallexample
861
862 To force point to move to the end of the new output no matter where
863it was previously, eliminate the variable @code{moving} and call
864@code{goto-char} unconditionally.
865
866 All filter functions that do regexp searching or matching should save
867and restore the match data. Otherwise, a filter function that runs
868during a call to @code{sit-for} might clobber the match data of the
869program that called @code{sit-for}. @xref{Match Data}.
870
871 A filter function that writes the output into the buffer of the
872process should check whether the process is still alive. If it tries to
873insert into a dead buffer, it will get an error. If the buffer is dead,
874@code{(buffer-name (process-buffer @var{process}))} returns @code{nil}.
875
876 The output to the function may come in chunks of any size. A program
877that produces the same output twice in a row may send it as one batch
878of 200 characters one time, and five batches of 40 characters the next.
879
880@defun set-process-filter process filter
881This function gives @var{process} the filter function @var{filter}. If
882@var{filter} is @code{nil}, it gives the process no filter.
883@end defun
884
885@defun process-filter process
886This function returns the filter function of @var{process}, or @code{nil}
887if it has none.
888@end defun
889
890 Here is an example of use of a filter function:
891
892@smallexample
893@group
894(defun keep-output (process output)
895 (setq kept (cons output kept)))
896 @result{} keep-output
897@end group
898@group
899(setq kept nil)
900 @result{} nil
901@end group
902@group
903(set-process-filter (get-process "shell") 'keep-output)
904 @result{} keep-output
905@end group
906@group
907(process-send-string "shell" "ls ~/other\n")
908 @result{} nil
909kept
910 @result{} ("lewis@@slug[8] % "
911@end group
912@group
913"FINAL-W87-SHORT.MSS backup.otl kolstad.mss~
914address.txt backup.psf kolstad.psf
915backup.bib~ david.mss resume-Dec-86.mss~
916backup.err david.psf resume-Dec.psf
917backup.mss dland syllabus.mss
918"
919"#backups.mss# backup.mss~ kolstad.mss
920")
921@end group
922@end smallexample
923
924@ignore @c The code in this example doesn't show the right way to do things.
925Here is another, more realistic example, which demonstrates how to use
926the process mark to do insertion in the same fashion as is done when
927there is no filter function:
928
929@smallexample
930@group
931;; @r{Insert input in the buffer specified by @code{my-shell-buffer}}
932;; @r{and make sure that buffer is shown in some window.}
933(defun my-process-filter (proc str)
934 (let ((cur (selected-window))
935 (pop-up-windows t))
936 (pop-to-buffer my-shell-buffer)
937@end group
938@group
939 (goto-char (point-max))
940 (insert str)
941 (set-marker (process-mark proc) (point-max))
942 (select-window cur)))
943@end group
944@end smallexample
945@end ignore
946
947@node Accepting Output
948@subsection Accepting Output from Processes
949
950 Output from asynchronous subprocesses normally arrives only while
951Emacs is waiting for some sort of external event, such as elapsed time
952or terminal input. Occasionally it is useful in a Lisp program to
953explicitly permit output to arrive at a specific point, or even to wait
954until output arrives from a process.
955
956@defun accept-process-output &optional process seconds millisec
957This function allows Emacs to read pending output from processes. The
958output is inserted in the associated buffers or given to their filter
959functions. If @var{process} is non-@code{nil} then this function does
960not return until some output has been received from @var{process}.
961
962@c Emacs 19 feature
963The arguments @var{seconds} and @var{millisec} let you specify timeout
964periods. The former specifies a period measured in seconds and the
965latter specifies one measured in milliseconds. The two time periods
966thus specified are added together, and @code{accept-process-output}
967returns after that much time whether or not there has been any
968subprocess output.
969
970Not all operating systems support waiting periods other than multiples
971of a second; on those that do not, you get an error if you specify
972nonzero @var{millisec}.
973
974The function @code{accept-process-output} returns non-@code{nil} if it
975did get some output, or @code{nil} if the timeout expired before output
976arrived.
977@end defun
978
979@node Sentinels
980@section Sentinels: Detecting Process Status Changes
981@cindex process sentinel
982@cindex sentinel
983
984 A @dfn{process sentinel} is a function that is called whenever the
985associated process changes status for any reason, including signals
986(whether sent by Emacs or caused by the process's own actions) that
987terminate, stop, or continue the process. The process sentinel is also
988called if the process exits. The sentinel receives two arguments: the
989process for which the event occurred, and a string describing the type
990of event.
991
992 The string describing the event looks like one of the following:
993
994@itemize @bullet
995@item
996@code{"finished\n"}.
997
998@item
999@code{"exited abnormally with code @var{exitcode}\n"}.
1000
1001@item
1002@code{"@var{name-of-signal}\n"}.
1003
1004@item
1005@code{"@var{name-of-signal} (core dumped)\n"}.
1006@end itemize
1007
1008 A sentinel runs only while Emacs is waiting (e.g., for terminal input,
1009or for time to elapse, or for process output). This avoids the timing
1010errors that could result from running them at random places in the
1011middle of other Lisp programs. A program can wait, so that sentinels
1012will run, by calling @code{sit-for}, @code{sleep-for} or
1013@code{accept-process-output} (@pxref{Accepting Output}). Emacs is also
1014waiting when the command loop is reading input.
1015
1016 Quitting is normally inhibited within a sentinel---otherwise, the
1017effect of typing @kbd{C-g} at command level or to quit a user command
1018would be unpredictable. If you want to permit quitting inside a
1019sentinel, bind @code{inhibit-quit} to @code{nil}. @xref{Quitting}.
1020
1021 A sentinel that writes the output into the buffer of the process
1022should check whether the process is still alive. If it tries to insert
1023into a dead buffer, it will get an error. If the buffer is dead,
1024@code{(buffer-name (process-buffer @var{process}))} returns @code{nil}.
1025
1026 All sentinels that do regexp searching or matching should save and
1027restore the match data. Otherwise, a sentinel that runs during a call
1028to @code{sit-for} might clobber the match data of the program that
1029called @code{sit-for}. @xref{Match Data}.
1030
1031@defun set-process-sentinel process sentinel
1032This function associates @var{sentinel} with @var{process}. If
1033@var{sentinel} is @code{nil}, then the process will have no sentinel.
1034The default behavior when there is no sentinel is to insert a message in
1035the process's buffer when the process status changes.
1036
1037@smallexample
1038@group
1039(defun msg-me (process event)
1040 (princ
1041 (format "Process: %s had the event `%s'" process event)))
1042(set-process-sentinel (get-process "shell") 'msg-me)
1043 @result{} msg-me
1044@end group
1045@group
1046(kill-process (get-process "shell"))
1047 @print{} Process: #<process shell> had the event `killed'
1048 @result{} #<process shell>
1049@end group
1050@end smallexample
1051@end defun
1052
1053@defun process-sentinel process
1054This function returns the sentinel of @var{process}, or @code{nil} if it
1055has none.
1056@end defun
1057
1058@defun waiting-for-user-input-p
1059While a sentinel or filter function is running, this function returns
1060non-@code{nil} if Emacs was waiting for keyboard input from the user at
1061the time the sentinel or filter function was called, @code{nil} if it
1062was not.
1063@end defun
1064
1065@node Transaction Queues
1066@section Transaction Queues
1067@cindex transaction queue
1068
1069You can use a @dfn{transaction queue} for more convenient communication
1070with subprocesses using transactions. First use @code{tq-create} to
1071create a transaction queue communicating with a specified process. Then
1072you can call @code{tq-enqueue} to send a transaction.
1073
1074@defun tq-create process
1075This function creates and returns a transaction queue communicating with
1076@var{process}. The argument @var{process} should be a subprocess
1077capable of sending and receiving streams of bytes. It may be a child
1078process, or it may be a TCP connection to a server possibly on another
1079machine.
1080@end defun
1081
1082@defun tq-enqueue queue question regexp closure fn
1083This function sends a transaction to queue @var{queue}. Specifying the
1084queue has the effect of specifying the subprocess to talk to.
1085
1086The argument @var{question} is the outgoing message which starts the
1087transaction. The argument @var{fn} is the function to call when the
1088corresponding answer comes back; it is called with two arguments:
1089@var{closure}, and the answer received.
1090
1091The argument @var{regexp} is a regular expression that should match the
1092entire answer, but nothing less; that's how @code{tq-enqueue} determines
1093where the answer ends.
1094
1095The return value of @code{tq-enqueue} itself is not meaningful.
1096@end defun
1097
1098@defun tq-close queue
1099Shut down transaction queue @var{queue}, waiting for all pending transactions
1100to complete, and then terminate the connection or child process.
1101@end defun
1102
1103Transaction queues are implemented by means of a filter function.
1104@xref{Filter Functions}.
1105
1106@node TCP
1107@section TCP
1108@cindex TCP
1109
1110 Emacs Lisp programs can open TCP connections to other processes on the
1111same machine or other machines. A network connection is handled by Lisp
1112much like a subprocess, and is represented by a process object.
1113However, the process you are communicating with is not a child of the
1114Emacs process, so you can't kill it or send it signals. All you can do
1115is send and receive data. @code{delete-process} closes the connection,
1116but does not kill the process at the other end; that process must decide
1117what to do about closure of the connection.
1118
1119 You can distinguish process objects representing network connections
1120from those representing subprocesses with the @code{process-status}
1121function. @xref{Process Information}.
1122
1123@defun open-network-stream name buffer-or-name host service
1124This function opens a TCP connection for a service to a host. It
1125returns a process object to represent the connection.
1126
1127The @var{name} argument specifies the name for the process object. It
1128is modified as necessary to make it unique.
1129
1130The @var{buffer-or-name} argument is the buffer to associate with the
1131connection. Output from the connection is inserted in the buffer,
1132unless you specify a filter function to handle the output. If
1133@var{buffer-or-name} is @code{nil}, it means that the connection is not
1134associated with any buffer.
1135
1136The arguments @var{host} and @var{service} specify where to connect to;
1137@var{host} is the host name (a string), and @var{service} is the name of
1138a defined network service (a string) or a port number (an integer).
1139@end defun
diff --git a/lispref/text.texi b/lispref/text.texi
new file mode 100644
index 00000000000..ccf43e72da6
--- /dev/null
+++ b/lispref/text.texi
@@ -0,0 +1,2658 @@
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/text
6@node Text, Searching and Matching, Markers, Top
7@chapter Text
8@cindex text
9
10 This chapter describes the functions that deal with the text in a
11buffer. Most examine, insert or delete text in the current buffer,
12often in the vicinity of point. Many are interactive. All the
13functions that change the text provide for undoing the changes
14(@pxref{Undo}).
15
16 Many text-related functions operate on a region of text defined by two
17buffer positions passed in arguments named @var{start} and @var{end}.
18These arguments should be either markers (@pxref{Markers}) or numeric
19character positions (@pxref{Positions}). The order of these arguments
20does not matter; it is all right for @var{start} to be the end of the
21region and @var{end} the beginning. For example, @code{(delete-region 1
2210)} and @code{(delete-region 10 1)} are equivalent. An
23@code{args-out-of-range} error is signaled if either @var{start} or
24@var{end} is outside the accessible portion of the buffer. In an
25interactive call, point and the mark are used for these arguments.
26
27@cindex buffer contents
28 Throughout this chapter, ``text'' refers to the characters in the
29buffer.
30
31@menu
32* Near Point:: Examining text in the vicinity of point.
33* Buffer Contents:: Examining text in a general fashion.
34* Comparing Text:: Comparing substrings of buffers.
35* Insertion:: Adding new text to a buffer.
36* Commands for Insertion:: User-level commands to insert text.
37* Deletion:: Removing text from a buffer.
38* User-Level Deletion:: User-level commands to delete text.
39* The Kill Ring:: Where removed text sometimes is saved for later use.
40* Undo:: Undoing changes to the text of a buffer.
41* Maintaining Undo:: How to enable and disable undo information.
42 How to control how much information is kept.
43* Filling:: Functions for explicit filling.
44* Auto Filling:: How auto-fill mode is implemented to break lines.
45* Sorting:: Functions for sorting parts of the buffer.
46* Columns:: Computing horizontal positions, and using them.
47* Indentation:: Functions to insert or adjust indentation.
48* Case Changes:: Case conversion of parts of the buffer.
49* Text Properties:: Assigning Lisp property lists to text characters.
50* Substitution:: Replacing a given character wherever it appears.
51* Registers:: How registers are implemented. Accessing the text or
52 position stored in a register.
53* Change Hooks:: Supplying functions to be run when text is changed.
54@end menu
55
56@node Near Point
57@section Examining Text Near Point
58
59 Many functions are provided to look at the characters around point.
60Several simple functions are described here. See also @code{looking-at}
61in @ref{Regexp Search}.
62
63@defun char-after position
64This function returns the character in the current buffer at (i.e.,
65immediately after) position @var{position}. If @var{position} is out of
66range for this purpose, either before the beginning of the buffer, or at
67or beyond the end, then the value is @code{nil}.
68
69In the following example, assume that the first character in the
70buffer is @samp{@@}:
71
72@example
73@group
74(char-to-string (char-after 1))
75 @result{} "@@"
76@end group
77@end example
78@end defun
79
80@defun following-char
81This function returns the character following point in the current
82buffer. This is similar to @code{(char-after (point))}. However, if
83point is at the end of the buffer, then @code{following-char} returns 0.
84
85Remember that point is always between characters, and the terminal
86cursor normally appears over the character following point. Therefore,
87the character returned by @code{following-char} is the character the
88cursor is over.
89
90In this example, point is between the @samp{a} and the @samp{c}.
91
92@example
93@group
94---------- Buffer: foo ----------
95Gentlemen may cry ``Pea@point{}ce! Peace!,''
96but there is no peace.
97---------- Buffer: foo ----------
98@end group
99
100@group
101(char-to-string (preceding-char))
102 @result{} "a"
103(char-to-string (following-char))
104 @result{} "c"
105@end group
106@end example
107@end defun
108
109@defun preceding-char
110This function returns the character preceding point in the current
111buffer. See above, under @code{following-char}, for an example. If
112point is at the beginning of the buffer, @code{preceding-char} returns
1130.
114@end defun
115
116@defun bobp
117This function returns @code{t} if point is at the beginning of the
118buffer. If narrowing is in effect, this means the beginning of the
119accessible portion of the text. See also @code{point-min} in
120@ref{Point}.
121@end defun
122
123@defun eobp
124This function returns @code{t} if point is at the end of the buffer.
125If narrowing is in effect, this means the end of accessible portion of
126the text. See also @code{point-max} in @xref{Point}.
127@end defun
128
129@defun bolp
130This function returns @code{t} if point is at the beginning of a line.
131@xref{Text Lines}. The beginning of the buffer (or its accessible
132portion always counts as the beginning of a line.
133@end defun
134
135@defun eolp
136This function returns @code{t} if point is at the end of a line. The
137end of the buffer (or of its accessible portion) is always considered
138the end of a line.
139@end defun
140
141@node Buffer Contents
142@section Examining Buffer Contents
143
144 This section describes two functions that allow a Lisp program to
145convert any portion of the text in the buffer into a string.
146
147@defun buffer-substring start end
148This function returns a string containing a copy of the text of the
149region defined by positions @var{start} and @var{end} in the current
150buffer. If the arguments are not positions in the accessible portion of
151the buffer, @code{buffer-substring} signals an @code{args-out-of-range}
152error.
153
154It is not necessary for @var{start} to be less than @var{end}; the
155arguments can be given in either order. But most often the smaller
156argument is written first.
157
158@example
159@group
160---------- Buffer: foo ----------
161This is the contents of buffer foo
162
163---------- Buffer: foo ----------
164@end group
165
166@group
167(buffer-substring 1 10)
168@result{} "This is t"
169@end group
170@group
171(buffer-substring (point-max) 10)
172@result{} "he contents of buffer foo
173"
174@end group
175@end example
176@end defun
177
178@defun buffer-string
179This function returns the contents of the accessible portion of the
180current buffer as a string. This is the portion between
181@code{(point-min)} and @code{(point-max)} (@pxref{Narrowing}).
182
183@example
184@group
185---------- Buffer: foo ----------
186This is the contents of buffer foo
187
188---------- Buffer: foo ----------
189
190(buffer-string)
191 @result{} "This is the contents of buffer foo
192"
193@end group
194@end example
195@end defun
196
197@node Comparing Text
198@section Comparing Text
199@cindex comparing buffer text
200
201 This function lets you compare portions of the text in a buffer, without
202copying them into strings first.
203
204@defun compare-buffer-substrings buffer1 start1 end1 buffer2 start2 end2
205This function lets you compare two substrings of the same buffer or two
206different buffers. The first three arguments specify one substring,
207giving a buffer and two positions within the buffer. The last three
208arguments specify the other substring in the same way. You can use
209@code{nil} for @var{buffer1}, @var{buffer2} or both to stand for the
210current buffer.
211
212The value is negative if the first substring is less, positive if the
213first is greater, and zero if they are equal. The absolute value of
214the result is one plus the index of the first differing characters
215within the substrings.
216
217This function ignores case when comparing characters
218if @code{case-fold-search} is non-@code{nil}.
219
220Suppose the current buffer contains the text @samp{foobarbar
221haha!rara!}; then in this example the two substrings are @samp{rbar }
222and @samp{rara!}. The value is 2 because the first substring is greater
223at the second character.
224
225@example
226(compare-buffer-substring nil 6 11 nil 16 21)
227 @result{} 2
228@end example
229
230This function does not exist in Emacs version 18 and earlier.
231@end defun
232
233@node Insertion
234@section Insertion
235@cindex insertion of text
236@cindex text insertion
237
238 @dfn{Insertion} means adding new text to a buffer. The inserted text
239goes at point---between the character before point and the character
240after point.
241
242 Insertion relocates markers that point at positions after the
243insertion point, so that they stay with the surrounding text
244(@pxref{Markers}). When a marker points at the place of insertion,
245insertion normally doesn't relocate the marker, so that it points to the
246beginning of the inserted text; however, certain special functions such
247as @code{insert-before-markers} relocate such markers to point after the
248inserted text.
249
250@cindex insertion before point
251@cindex before point, insertion
252 Some insertion functions leave point before the inserted text, while
253other functions leave it after. We call the latter insertion
254@dfn{before point}.
255
256 Insertion functions signal an error if the current buffer is
257read-only.
258
259@defun insert &rest args
260This function inserts the strings and/or characters @var{args} into the
261current buffer, at point, moving point forward. An error is signaled
262unless all @var{args} are either strings or characters. The value is
263@code{nil}.
264@end defun
265
266@defun insert-before-markers &rest args
267This function inserts the strings and/or characters @var{args} into the
268current buffer, at point, moving point forward. An error is signaled
269unless all @var{args} are either strings or characters. The value is
270@code{nil}.
271
272This function is unlike the other insertion functions in that it
273relocates markers initially pointing at the insertion point, to point
274after the inserted text.
275@end defun
276
277@defun insert-char character count
278This function inserts @var{count} instances of @var{character} into the
279current buffer before point. The argument @var{count} must be a number,
280and @var{character} must be a character. The value is @code{nil}.
281@c It's unfortunate that count comes second. Not like make-string, etc.
282@end defun
283
284@defun insert-buffer-substring from-buffer-or-name &optional start end
285This function inserts a portion of buffer @var{from-buffer-or-name}
286(which must already exist) into the current buffer before point. The
287text inserted is the region from @var{start} and @var{end}. (These
288arguments default to the beginning and end of the accessible portion of
289that buffer.) This function returns @code{nil}.
290
291In this example, the form is executed with buffer @samp{bar} as the
292current buffer. We assume that buffer @samp{bar} is initially empty.
293
294@example
295@group
296---------- Buffer: foo ----------
297We hold these truths to be self-evident, that all
298---------- Buffer: foo ----------
299@end group
300
301@group
302(insert-buffer-substring "foo" 1 20)
303 @result{} nil
304
305---------- Buffer: bar ----------
306We hold these truth
307---------- Buffer: bar ----------
308@end group
309@end example
310@end defun
311
312 @xref{Sticky Properties}, for other insertion functions that inherit
313text properties from the nearby text.
314
315@node Commands for Insertion
316@section User-Level Insertion Commands
317
318 This section describes higher-level commands for inserting text,
319commands intended primarily for the user but useful also in Lisp
320programs.
321
322@deffn Command insert-buffer from-buffer-or-name
323This command inserts the entire contents of @var{from-buffer-or-name}
324(which must exist) into the current buffer after point. It leaves
325the mark after the inserted text. The value is @code{nil}.
326@end deffn
327
328@deffn Command self-insert-command count
329@cindex character insertion
330@cindex self-insertion
331This command inserts the last character typed @var{count} times and
332returns @code{nil}. Most printing characters are bound to this command.
333In routine use, @code{self-insert-command} is the most frequently called
334function in Emacs, but programs rarely use it except to install it on a
335keymap.
336
337In an interactive call, @var{count} is the numeric prefix argument.
338
339This function calls @code{auto-fill-function} if the current column number
340is greater than the value of @code{fill-column} and the character
341inserted is a space (@pxref{Auto Filling}).
342
343@c Cross refs reworded to prevent overfull hbox. --rjc 15mar92
344This function performs abbrev expansion if Abbrev mode is enabled and
345the inserted character does not have word-constituent
346syntax. (@xref{Abbrevs}, and @ref{Syntax Class Table}.)
347
348This function is also responsible for calling
349@code{blink-paren-function} when the inserted character has close
350parenthesis syntax (@pxref{Blinking}).
351@end deffn
352
353@deffn Command newline &optional number-of-newlines
354This command inserts newlines into the current buffer before point.
355If @var{number-of-newlines} is supplied, that many newline characters
356are inserted.
357
358@cindex newline and Auto Fill mode
359In Auto Fill mode, @code{newline} can break the preceding line if
360@var{number-of-newlines} is not supplied. When this happens, it
361actually inserts two newlines at different places: one at point, and
362another earlier in the line. @code{newline} does not auto-fill if
363@var{number-of-newlines} is non-@code{nil}.
364
365The value returned is @code{nil}. In an interactive call, @var{count}
366is the numeric prefix argument.
367@end deffn
368
369@deffn Command split-line
370This command splits the current line, moving the portion of the line
371after point down vertically, so that it is on the next line directly
372below where it was before. Whitespace is inserted as needed at the
373beginning of the lower line, using the @code{indent-to} function.
374@code{split-line} returns the position of point.
375
376Programs hardly ever use this function.
377@end deffn
378
379@defvar overwrite-mode
380This variable controls whether overwrite mode is in effect: a
381non-@code{nil} value enables the mode. It is automatically made
382buffer-local when set in any fashion.
383@end defvar
384
385@node Deletion
386@section Deletion of Text
387
388@cindex deletion vs killing
389 Deletion means removing part of the text in a buffer, without saving
390it in the kill ring (@pxref{The Kill Ring}). Deleted text can't be
391yanked, but can be reinserted using the undo mechanism (@pxref{Undo}).
392Some deletion functions save text in the kill ring in some cases
393but not in the usual case.
394
395 All of the deletion functions operate on the current buffer, and all
396return a value of @code{nil}.
397
398@defun erase-buffer
399This function deletes the entire text of the current buffer, leaving it
400empty. If the buffer is read-only, it signals a @code{buffer-read-only}
401error. Otherwise, it deletes the text without asking for any
402confirmation. It returns @code{nil}.
403
404Normally, deleting a large amount of text from a buffer inhibits further
405auto-saving of that buffer ``because it has shrunk''. However,
406@code{erase-buffer} does not do this, the idea being that the future
407text is not really related to the former text, and its size should not
408be compared with that of the former text.
409@end defun
410
411@deffn Command delete-region start end
412This command deletes the text in the current buffer in the region
413defined by @var{start} and @var{end}. The value is @code{nil}.
414@end deffn
415
416@deffn Command delete-char count &optional killp
417This command deletes @var{count} characters directly after point, or
418before point if @var{count} is negative. If @var{killp} is
419non-@code{nil}, then it saves the deleted characters in the kill ring.
420
421In an interactive call, @var{count} is the numeric prefix argument, and
422@var{killp} is the unprocessed prefix argument. Therefore, if a prefix
423argument is supplied, the text is saved in the kill ring. If no prefix
424argument is supplied, then one character is deleted, but not saved in
425the kill ring.
426
427The value returned is always @code{nil}.
428@end deffn
429
430@deffn Command delete-backward-char count &optional killp
431@cindex delete previous char
432This command deletes @var{count} characters directly before point, or
433after point if @var{count} is negative. If @var{killp} is
434non-@code{nil}, then it saves the deleted characters in the kill ring.
435
436In an interactive call, @var{count} is the numeric prefix argument, and
437@var{killp} is the unprocessed prefix argument. Therefore, if a prefix
438argument is supplied, the text is saved in the kill ring. If no prefix
439argument is supplied, then one character is deleted, but not saved in
440the kill ring.
441
442The value returned is always @code{nil}.
443@end deffn
444
445@deffn Command backward-delete-char-untabify count &optional killp
446@cindex tab deletion
447This command deletes @var{count} characters backward, changing tabs
448into spaces. When the next character to be deleted is a tab, it is
449first replaced with the proper number of spaces to preserve alignment
450and then one of those spaces is deleted instead of the tab. If
451@var{killp} is non-@code{nil}, then the command saves the deleted
452characters in the kill ring.
453
454Conversion of tabs to spaces happens only if @var{count} is positive.
455If it is negative, exactly @minus{}@var{count} characters after point
456are deleted.
457
458In an interactive call, @var{count} is the numeric prefix argument, and
459@var{killp} is the unprocessed prefix argument. Therefore, if a prefix
460argument is supplied, the text is saved in the kill ring. If no prefix
461argument is supplied, then one character is deleted, but not saved in
462the kill ring.
463
464The value returned is always @code{nil}.
465@end deffn
466
467@node User-Level Deletion
468@section User-Level Deletion Commands
469
470 This section describes higher-level commands for deleting text,
471commands intended primarily for the user but useful also in Lisp
472programs.
473
474@deffn Command delete-horizontal-space
475@cindex deleting whitespace
476This function deletes all spaces and tabs around point. It returns
477@code{nil}.
478
479In the following examples, we call @code{delete-horizontal-space} four
480times, once on each line, with point between the second and third
481characters on the successive line.
482
483@example
484@group
485---------- Buffer: foo ----------
486I @point{}thought
487I @point{} thought
488We@point{} thought
489Yo@point{}u thought
490---------- Buffer: foo ----------
491@end group
492
493@group
494(delete-horizontal-space) ; @r{Four times.}
495 @result{} nil
496
497---------- Buffer: foo ----------
498Ithought
499Ithought
500Wethought
501You thought
502---------- Buffer: foo ----------
503@end group
504@end example
505@end deffn
506
507@deffn Command delete-indentation &optional join-following-p
508This function joins the line point is on to the previous line, deleting
509any whitespace at the join and in some cases replacing it with one
510space. If @var{join-following-p} is non-@code{nil},
511@code{delete-indentation} joins this line to the following line
512instead. The value is @code{nil}.
513
514If there is a fill prefix, and the second of the lines being joined
515starts with the prefix, then @code{delete-indentation} deletes the
516fill prefix before joining the lines.
517
518In the example below, point is located on the line starting
519@samp{events}, and it makes no difference if there are trailing spaces
520in the preceding line.
521
522@smallexample
523---------- Buffer: foo ----------
524When in the course of human
525@point{} events, it becomes necessary
526---------- Buffer: foo ----------
527
528(delete-indentation)
529 @result{} nil
530
531---------- Buffer: foo ----------
532When in the course of human@point{} events, it becomes necessary
533---------- Buffer: foo ----------
534@end smallexample
535
536After the lines are joined, the function @code{fixup-whitespace} is
537responsible for deciding whether to leave a space at the junction.
538@end deffn
539
540@defun fixup-whitespace
541This function replaces all the white space surrounding point with either
542one space or no space, according to the context. It returns @code{nil}.
543
544At the beginning or end of a line, the appropriate amount of space is
545none. Before a character with close parenthesis syntax, or after a
546character with open parenthesis or expression-prefix syntax, no space is
547also appropriate. Otherwise, one space is appropriate. @xref{Syntax
548Class Table}.
549
550In the example below, @code{fixup-whitespace} is called the first time
551with point before the word @samp{spaces} in the first line. for the
552second invocation, Point is directly after the @samp{(}.
553
554@smallexample
555@group
556---------- Buffer: foo ----------
557This has too many @point{}spaces
558This has too many spaces at the start of (@point{} this list)
559---------- Buffer: foo ----------
560@end group
561
562@group
563(fixup-whitespace)
564 @result{} nil
565(fixup-whitespace)
566 @result{} nil
567@end group
568
569@group
570---------- Buffer: foo ----------
571This has too many spaces
572This has too many spaces at the start of (this list)
573---------- Buffer: foo ----------
574@end group
575@end smallexample
576@end defun
577
578@deffn Command just-one-space
579@comment !!SourceFile simple.el
580This command replaces any spaces and tabs around point with a single
581space. It returns @code{nil}.
582@end deffn
583
584@deffn Command delete-blank-lines
585This function deletes blank lines surrounding point. If point is on a
586blank line with one or more blank lines before or after it, then all but
587one of them are deleted. If point is on an isolated blank line, then it
588is deleted. If point is on a nonblank line, the command deletes all
589blank lines following it.
590
591A blank line is defined as a line containing only tabs and spaces.
592
593@code{delete-blank-lines} returns @code{nil}.
594@end deffn
595
596@node The Kill Ring
597@section The Kill Ring
598@cindex kill ring
599
600 @dfn{Kill} functions delete text like the deletion functions, but save
601it so that the user can reinsert it by @dfn{yanking}. Most of these
602functions have @samp{kill-} in their name. By contrast, the functions
603whose names start with @samp{delete-} normally do not save text for
604yanking (though they can still be undone); these are ``deletion''
605functions.
606
607 Most of the kill commands are primarily for interactive use, and are
608not described here. What we do describe are the functions provided for
609use in writing such commands. You can use these functions to write
610commands for killing text. When you need to deleting text for internal
611purposes within a Lisp function, you should normally use deletion
612functions, so as not to disturb the kill ring contents.
613@xref{Deletion}.
614
615 Killed text is saved for later yanking in the @dfn{kill ring}. This
616is a list which holds, not just the last text kill, but a number of
617recent kills. We call this a ``ring'' because yanking treats it as a
618cyclic order. The list is kept in the variable @code{kill-ring}, and
619can be operated on with the usual functions for lists; there are also
620specialized functions, described in this section, which treat it as a
621ring.
622
623 Some people think this use of the word ``kill'' is unfortunate, since
624it refers to operations which specifically @emph{do not} destroy the
625entities ``killed''. This is in sharp contrast to ordinary life, in
626which death is permanent and ``killed'' entities do not come back to
627life. Therefore, other metaphors have been proposed. For example, the
628term ``cut ring'' makes sense to people who, in pre-computer days, used
629scissors and paste to cut up and rearrange manuscripts. However, it
630would be difficult to change the terminology now.
631
632@menu
633* Kill Ring Concepts:: What text looks like in the kill ring.
634* Kill Functions:: Functions that kill text.
635* Yank Commands:: Commands that access the kill ring.
636* Low Level Kill Ring:: Functions and variables for kill ring access.
637* Internals of Kill Ring:: Variables that hold kill-ring data.
638@end menu
639
640@node Kill Ring Concepts
641@comment node-name, next, previous, up
642@subsection Kill Ring Concepts
643
644 The kill ring records killed text as strings in a list, most recent
645first. A short kill ring, for example, might look like this:
646
647@example
648("some text" "a different piece of text" "even older text")
649@end example
650
651@noindent
652When the list reaches @code{kill-ring-max} entries in length, adding a
653new entry automatically deletes the last entry.
654
655 When kill commands are interwoven with other commands, each kill
656command makes a new entry in the kill ring. Multiple kill commands in
657succession build up a single entry in the kill ring, which would be
658yanked as a unit. The second and subsequent consecutive kill commands
659add text to the entry made by the first one.
660
661 For yanking, one entry in the kill ring is designated the ``front'' of
662the ring. Some yank commands ``rotate'' the ring by designating a
663different element as the ``front.'' But this virtual rotation doesn't
664change the list itself---the most recent entry always comes first in the
665list.
666
667@node Kill Functions
668@comment node-name, next, previous, up
669@subsection Functions for Killing
670
671 @code{kill-region} is the usual subroutine for killing text. Any
672command that calls this function is a ``kill command'' (and should
673probably have @samp{kill} in its name). @code{kill-region} puts the
674newly killed text in a new element at the beginning of the kill ring or
675adds it to the most recent element. It uses the @code{last-command}
676variable to determine whether the previous was a kill command, and if so
677appends the killed text to the most recent entry.
678
679@deffn Command kill-region start end
680This function kills the text in the region defined by @var{start} and
681@var{end}. The text is deleted but saved in the kill ring. The value
682is always @code{nil}.
683
684In an interactive call, @var{start} and @var{end} are point and
685the mark.
686
687@c Emacs 19 feature
688If the buffer is read-only, @code{kill-region} modifies the kill ring
689just the same, then signals an error without modifying the buffer. This
690is convenient because it lets the user use all the kill commands to copy
691text into the kill ring from a read-only buffer.
692@end deffn
693
694@deffn Command copy-region-as-kill start end
695This command saves the region defined by @var{start} and @var{end} on
696the kill ring, but does not delete the text from the buffer. It returns
697@code{nil}. It also indicates the extent of the text copied by moving
698the cursor momentarily, or by displaying a message in the echo area.
699
700Don't call @code{copy-region-as-kill} in Lisp programs unless you aim to
701support Emacs 18. For Emacs 19, it is better to use @code{kill-new} or
702@code{kill-append} instead. @xref{Low Level Kill Ring}.
703@end deffn
704
705@node Yank Commands
706@comment node-name, next, previous, up
707@subsection Functions for Yanking
708
709 @dfn{Yanking} means reinserting an entry of previously killed text
710from the kill ring.
711
712@deffn Command yank &optional arg
713@cindex inserting killed text
714This command inserts before point the text in the first entry in the
715kill ring. It positions the mark at the beginning of that text, and
716point at the end.
717
718If @var{arg} is a list (which occurs interactively when the user
719types @kbd{C-u} with no digits), then @code{yank} inserts the text as
720described above, but puts point before the yanked text and puts the mark
721after it.
722
723If @var{arg} is a number, then @code{yank} inserts the @var{arg}th most
724recently killed text---the @var{arg}th element of the kill ring list.
725
726@code{yank} does not alter the contents of the kill ring or rotate it.
727It returns @code{nil}.
728@end deffn
729
730@deffn Command yank-pop arg
731This command replaces the just-yanked entry from the kill ring with a
732different entry from the kill ring.
733
734This is allowed only immediately after a @code{yank} or another
735@code{yank-pop}. At such a time, the region contains text that was just
736inserted by yanking. @code{yank-pop} deletes that text and inserts in
737its place a different piece of killed text. It does not add the deleted
738text to the kill ring, since it is already in the kill ring somewhere.
739
740If @var{arg} is @code{nil}, then the replacement text is the previous
741element of the kill ring. If @var{arg} is numeric, the replacement is
742the @var{arg}th previous kill. If @var{arg} is negative, a more recent
743kill is the replacement.
744
745The sequence of kills in the kill ring wraps around, so that after the
746oldest one comes the newest one, and before the newest one goes the
747oldest.
748
749The value is always @code{nil}.
750@end deffn
751
752@node Low Level Kill Ring
753@subsection Low Level Kill Ring
754
755 These functions and variables provide access to the kill ring at a lower
756level, but still convenient for use in Lisp programs. They take care of
757interaction with X Window selections. They do not exist in Emacs
758version 18.
759
760@defun current-kill n &optional do-not-move
761The function @code{current-kill} rotates the yanking pointer in the
762kill ring by @var{n} places, and returns the text at that place in the
763ring.
764
765If the optional second argument @var{do-not-move} is non-@code{nil},
766then @code{current-kill} doesn't alter the yanking pointer; it just
767returns the @var{n}th kill forward from the current yanking pointer.
768
769If @var{n} is zero, indicating a request for the latest kill,
770@code{current-kill} calls the value of
771@code{interprogram-paste-function} (documented below) before consulting
772the kill ring.
773@end defun
774
775@defun kill-new string
776This function puts the text @var{string} into the kill ring as a new
777entry at the front of the ring. It discards the oldest entry if
778appropriate. It also invokes the value of
779@code{interprogram-cut-function} (see below).
780@end defun
781
782@defun kill-append string before-p
783This function appends the text @var{string} to the first entry in the
784kill ring. Normally @var{string} goes at the end of the entry, but if
785@var{before-p} is non-@code{nil}, it goes at the beginning. This
786function also invokes the value of @code{interprogram-cut-function} (see
787below).
788@end defun
789
790@defvar interprogram-paste-function
791This variable provides a way of transferring killed text from other
792programs, when you are using a window system. Its value should be
793@code{nil} or a function of no arguments.
794
795If the value is a function, @code{current-kill} calls it to get the
796``most recent kill''. If the function returns a non-@code{nil} value,
797then that value is used as the ``most recent kill''. If it returns
798@code{nil}, then the first element of @code{kill-ring} is used.
799
800The normal use of this hook is to get the X server's primary selection
801as the most recent kill, even if the selection belongs to another X
802client. @xref{X Selections}.
803@end defvar
804
805@defvar interprogram-cut-function
806This variable provides a way of communicating killed text to and from
807other programs, when you are using a window system. Its value should be
808@code{nil} or a function of one argument.
809
810If the value is a function, @code{kill-new} and @code{kill-append} call
811it with the new first element of the kill ring as an argument.
812
813The normal use of this hook is to set the X server's primary selection
814to the newly killed text.
815@end defvar
816
817@node Internals of Kill Ring
818@comment node-name, next, previous, up
819@subsection Internals of the Kill Ring
820
821 The variable @code{kill-ring} holds the kill ring contents, in the
822form of a list of strings. The most recent kill is always at the front
823of the list.
824
825 The @code{kill-ring-yank-pointer} variable points to a link in the
826kill ring list, whose @sc{car} is the text to yank next. Moving
827@code{kill-ring-yank-pointer} to a different link is called
828@dfn{rotating the kill ring}; we say it identifies the ``front'' of the
829ring. We call the kill ring a ``ring'' because the functions that move
830the yank pointer wrap around from the end of the list to the beginning,
831or vice-versa. Rotation of the kill ring is virtual; it does not change
832the value of @code{kill-ring}.
833
834 Both @code{kill-ring} and @code{kill-ring-yank-pointer} are Lisp
835variables whose values are normally lists. The word ``pointer'' in the
836name of the @code{kill-ring-yank-pointer} indicates that the variable's
837purpose is to identify one element of the list for use by the next yank
838command.
839
840 The value of @code{kill-ring-yank-pointer} is always @code{eq} to one
841of the links in the kill ring list. The element it identifies is the
842@sc{car} of that link. Kill commands, which change the kill ring, also
843set this variable from @code{kill-ring}. The effect is to rotate the
844ring so that the newly killed text is at front.
845
846 Here is a diagram that shows the variable @code{kill-ring-yank-pointer}
847pointing to the second entry in the kill ring @code{("some text" "a
848different piece of text" "yet older text")}.
849
850@example
851@group
852kill-ring kill-ring-yank-pointer
853 | |
854 | ___ ___ ---> ___ ___ ___ ___
855 --> |___|___|------> |___|___|--> |___|___|--> nil
856 | | |
857 | | |
858 | | -->"yet older text"
859 | |
860 | --> "a different piece of text"
861 |
862 --> "some text"
863@end group
864@end example
865
866@noindent
867This state of affairs might occur after @kbd{C-y} (@code{yank})
868immediately followed by @kbd{M-y} (@code{yank-pop}).
869
870@defvar kill-ring
871This variable holds list of killed text sequences, most recently killed
872first.
873@end defvar
874
875@defvar kill-ring-yank-pointer
876This variable's value indicates which element of the kill ring is at the
877``front'' of the ring for yanking. More precisely, the value is a tail
878of the value of @code{kill-ring}, and its @sc{car} is the kill string
879that @kbd{C-y} should yank.
880@end defvar
881
882@defopt kill-ring-max
883The value of this variable is the maximum length to which the kill
884ring can grow, before elements are thrown away at the end. The default
885value for @code{kill-ring-max} is 30.
886@end defopt
887
888@node Undo
889@comment node-name, next, previous, up
890@section Undo
891@cindex redo
892
893 Most buffers have an @dfn{undo list} which records all changes made to
894the buffer's text so that they can be undone. (The buffers which don't
895have one are usually special-purpose buffers for which Emacs assumes
896that undoing is not useful.) All the primitives which modify the text
897in the buffer automatically add elements to the front of the undo list,
898which is in the variable @code{buffer-undo-list}.
899
900@defvar buffer-undo-list
901This variable's value is the undo list of the current buffer.
902A value of @code{t} disables the recording of undo information.
903@end defvar
904
905Here are the kinds of elements an undo list can have:
906
907@table @code
908@item @var{integer}
909This kind of element records a previous value of point. Ordinary cursor
910motion does not get any sort of undo record, but deletion commands use
911these entries to record where point was before the command.
912
913@item (@var{beg} . @var{end})
914This kind of element indicates how to delete text that was inserted.
915Upon insertion, the text occupied the range @var{beg}--@var{end} in the
916buffer.
917
918@item (@var{pos} . @var{deleted})
919This kind of element indicates how to reinsert text that was deleted.
920The deleted text itself is the string @var{deleted}. The place to
921reinsert it is @var{pos}.
922
923@item (t @var{high} . @var{low})
924This kind of element indicates that an unmodified buffer became
925modified. The elements @var{high} and @var{low} are two integers, each
926recording 16 bits of the visited file's modification time as of when it
927was previously visited or saved. @code{primitive-undo} uses those
928values to determine whether to mark the buffer as unmodified once again;
929it does so only if the file's modification time matches those numbers.
930
931@item (nil @var{property} @var{value} @var{beg} . @var{end})
932This kind of element records a change in a text property.
933Here's how you might undo the change:
934
935@example
936(put-text-property @var{beg} @var{end} @var{property} @var{value})
937@end example
938
939@item nil
940This element is a boundary. The elements between two boundaries are
941called a @dfn{change group}; normally, each change group corresponds to
942one keyboard command, and undo commands normally undo an entire group as
943a unit.
944@end table
945
946@defun undo-boundary
947This function places a boundary element in the undo list. The undo
948command stops at such a boundary, and successive undo commands undo
949to earlier and earlier boundaries. This function returns @code{nil}.
950
951The editor command loop automatically creates an undo boundary between
952keystroke commands. Thus, each undo normally undoes the effects of one
953command. Calling this function explicitly is useful for splitting the
954effects of a command into more than one unit. For example,
955@code{query-replace} calls this function after each replacement so that
956the user can undo individual replacements one by one.
957@end defun
958
959@defun primitive-undo count list
960This is the basic function for undoing elements of an undo list.
961It undoes the first @var{count} elements of @var{list}, returning
962the rest of @var{list}. You could write this function in Lisp,
963but it is convenient to have it in C.
964
965@code{primitive-undo} adds elements to the buffer's undo list when it
966changes the buffer. Undo commands avoid confusion by saving the undo
967list value at the beginning of a sequence of undo operations. Then the
968undo operations use and update the saved value. The new elements added
969by undoing are not part of the saved value, so they don't interfere with
970continuing to undo.
971@end defun
972
973@node Maintaining Undo
974@section Maintaining Undo Lists
975
976 This section describes how to enable and disable undo information for
977a given buffer. It also explains how the undo list is truncated
978automatically so it doesn't get too big.
979
980 Recording of undo information in a newly created buffer is normally
981enabled to start with; but if the buffer name starts with a space, the
982undo recording is initially disabled. You can explicitly enable or
983disable undo recording with the following two functions, or by setting
984@code{buffer-undo-list} yourself.
985
986@deffn Command buffer-enable-undo &optional buffer-or-name
987This command enables recording undo information for buffer
988@var{buffer-or-name}, so that subsequent changes can be undone. If no
989argument is supplied, then the current buffer is used. This function
990does nothing if undo recording is already enabled in the buffer. It
991returns @code{nil}.
992
993In an interactive call, @var{buffer-or-name} is the current buffer.
994You cannot specify any other buffer.
995@end deffn
996
997@defun buffer-disable-undo &optional buffer
998@defunx buffer-flush-undo &optional buffer
999@cindex disable undo
1000This function discards the undo list of @var{buffer}, and disables
1001further recording of undo information. As a result, it is no longer
1002possible to undo either previous changes or any subsequent changes. If
1003the undo list of @var{buffer} is already disabled, this function
1004has no effect.
1005
1006This function returns @code{nil}. It cannot be called interactively.
1007
1008The name @code{buffer-flush-undo} is not considered obsolete, but the
1009preferred name @code{buffer-disable-undo} is new as of Emacs versions
101019.
1011@end defun
1012
1013 As editing continues, undo lists get longer and longer. To prevent
1014them from using up all available memory space, garbage collection trims
1015them back to size limits you can set. (For this purpose, the ``size''
1016of an undo list measures the cons cells that make up the list, plus the
1017strings of deleted text.) Two variables control the range of acceptable
1018sizes: @code{undo-limit} and @code{undo-strong-limit}.
1019
1020@defvar undo-limit
1021This is the soft limit for the acceptable size of an undo list. The
1022change group at which this size is exceeded is the last one kept.
1023@end defvar
1024
1025@defvar undo-strong-limit
1026The upper limit for the acceptable size of an undo list. The change
1027group at which this size is exceeded is discarded itself (along with all
1028subsequent changes). There is one exception: garbage collection always
1029keeps the very latest change group no matter how big it is.
1030@end defvar
1031
1032@node Filling
1033@comment node-name, next, previous, up
1034@section Filling
1035@cindex filling, explicit
1036
1037 @dfn{Filling} means adjusting the lengths of lines (by moving the line
1038breaks) so that they are nearly (but no greater than) a specified
1039maximum width. Additionally, lines can be @dfn{justified}, which means
1040that spaces are inserted between words to make the line exactly the
1041specified width. The width is controlled by the variable
1042@code{fill-column}. For ease of reading, lines should be no longer than
104370 or so columns.
1044
1045 You can use Auto Fill mode (@pxref{Auto Filling}) to fill text
1046automatically as you insert it, but changes to existing text may leave
1047it improperly filled. Then you must fill the text explicitly.
1048
1049 Most of the functions in this section return values that are not
1050meaningful.
1051
1052@deffn Command fill-paragraph justify-flag
1053@cindex filling a paragraph
1054This command fills the paragraph at or after point. If
1055@var{justify-flag} is non-@code{nil}, each line is justified as well.
1056It uses the ordinary paragraph motion commands to find paragraph
1057boundaries. @xref{Paragraphs,,, emacs, The Emacs Manual}.
1058@end deffn
1059
1060@deffn Command fill-region start end &optional justify-flag
1061This command fills each of the paragraphs in the region from @var{start}
1062to @var{end}. It justifies as well if @var{justify-flag} is
1063non-@code{nil}.
1064
1065The variable @code{paragraph-separate} controls how to distinguish
1066paragraphs. @xref{Standard Regexps}.
1067@end deffn
1068
1069@deffn Command fill-individual-paragraphs start end &optional justify-flag mail-flag
1070This command fills each paragraph in the region according to its
1071individual fill prefix. Thus, if the lines of a paragraph were indented
1072with spaces, the filled paragraph will remain indented in the same
1073fashion.
1074
1075The first two arguments, @var{start} and @var{end}, are the beginning
1076and end of the region to be filled. The third and fourth arguments,
1077@var{justify-flag} and @var{mail-flag}, are optional. If
1078@var{justify-flag} is non-@code{nil}, the paragraphs are justified as
1079well as filled. If @var{mail-flag} is non-@code{nil}, it means the
1080function is operating on a mail message and therefore should not fill
1081the header lines.
1082
1083Ordinarily, @code{fill-individual-paragraphs} regards each change in
1084indentation as starting a new paragraph. If
1085@code{fill-individual-varying-indent} is non-@code{nil}, then only
1086separator lines separate paragraphs. That mode can handle paragraphs
1087with extra indentation on the first line.
1088@end deffn
1089
1090@defopt fill-individual-varying-indent
1091This variable alters the action of @code{fill-individual-paragraphs} as
1092described above.
1093@end defopt
1094
1095@deffn Command fill-region-as-paragraph start end &optional justify-flag
1096This command considers a region of text as a paragraph and fills it. If
1097the region was made up of many paragraphs, the blank lines between
1098paragraphs are removed. This function justifies as well as filling when
1099@var{justify-flag} is non-@code{nil}. In an interactive call, any
1100prefix argument requests justification.
1101
1102In Adaptive Fill mode, which is enabled by default,
1103@code{fill-region-as-paragraph} on an indented paragraph when there is
1104no fill prefix uses the indentation of the second line of the paragraph
1105as the fill prefix.
1106@end deffn
1107
1108@deffn Command justify-current-line
1109This command inserts spaces between the words of the current line so
1110that the line ends exactly at @code{fill-column}. It returns
1111@code{nil}.
1112@end deffn
1113
1114@defopt fill-column
1115This buffer-local variable specifies the maximum width of filled
1116lines. Its value should be an integer, which is a number of columns.
1117All the filling, justification and centering commands are affected by
1118this variable, including Auto Fill mode (@pxref{Auto Filling}).
1119
1120As a practical matter, if you are writing text for other people to
1121read, you should set @code{fill-column} to no more than 70. Otherwise
1122the line will be too long for people to read comfortably, and this can
1123make the text seem clumsy.
1124@end defopt
1125
1126@defvar default-fill-column
1127The value of this variable is the default value for @code{fill-column} in
1128buffers that do not override it. This is the same as
1129@code{(default-value 'fill-column)}.
1130
1131The default value for @code{default-fill-column} is 70.
1132@end defvar
1133
1134@node Auto Filling
1135@comment node-name, next, previous, up
1136@section Auto Filling
1137@cindex filling, automatic
1138@cindex Auto Fill mode
1139
1140 Auto Fill mode is a minor mode which fills lines automatically as text
1141as inserted. This section describes the hook and the two variables used
1142by Auto Fill mode. For a description of functions that you can call
1143explicitly to fill and justify existing text, see @ref{Filling}.
1144
1145@defvar auto-fill-function
1146The value of this variable should be a function (of no arguments) to
1147be called after self-inserting a space at a column beyond
1148@code{fill-column}. It may be @code{nil}, in which case nothing
1149special is done.
1150
1151The value of @code{auto-fill-function} is @code{do-auto-fill} when
1152Auto-Fill mode is enabled. That is a function whose sole purpose is to
1153implement the usual strategy for breaking a line.
1154
1155@quotation
1156In older Emacs versions, this variable was named @code{auto-fill-hook},
1157but since it is not called with the standard convention for hooks, it
1158was renamed to @code{auto-fill-function} in version 19.
1159@end quotation
1160@end defvar
1161
1162@node Sorting
1163@section Sorting Text
1164@cindex sorting text
1165
1166 The sorting functions described in this section all rearrange text in
1167a buffer. This is in contrast to the function @code{sort}, which
1168rearranges the order of the elements of a list (@pxref{Rearrangement}).
1169The values returned by these functions are not meaningful.
1170
1171@defun sort-subr reverse nextrecfun endrecfun &optional startkeyfun endkeyfun
1172This function is the general text sorting routine that divides a buffer
1173into records and sorts them. Most of the commands in this section use
1174this function.
1175
1176To understand how @code{sort-subr} works, consider the whole accessible
1177portion of the buffer as being divided into disjoint pieces called
1178@dfn{sort records}. The records may or may not be contiguous; they may
1179not overlap. A portion of each sort record (perhaps all of it) is
1180designated as the sort key. Sorting rearranges the records in order by
1181their sort keys.
1182
1183Usually, the records are rearranged in order of ascending sort key.
1184If the first argument to the @code{sort-subr} function, @var{reverse},
1185is non-@code{nil}, the sort records are rearranged in order of
1186descending sort key.
1187
1188The next four arguments to @code{sort-subr} are functions that are
1189called to move point across a sort record. They are called many times
1190from within @code{sort-subr}.
1191
1192@enumerate
1193@item
1194@var{nextrecfun} is called with point at the end of a record. This
1195function moves point to the start of the next record. The first record
1196is assumed to start at the position of point when @code{sort-subr} is
1197called. Therefore, you should usually move point to the beginning of
1198the buffer before calling @code{sort-subr}.
1199
1200This function can indicate there are no more sort records by leaving
1201point at the end of the buffer.
1202
1203@item
1204@var{endrecfun} is called with point within a record. It moves point to
1205the end of the record.
1206
1207@item
1208@var{startkeyfun} is called to move point from the start of a record to
1209the start of the sort key. This argument is optional; if it is omitted,
1210the whole record is the sort key. If supplied, the function should
1211either return a non-@code{nil} value to be used as the sort key, or
1212return @code{nil} to indicate that the sort key is in the buffer
1213starting at point. In the latter case, @var{endkeyfun} is called to
1214find the end of the sort key.
1215
1216@item
1217@var{endkeyfun} is called to move point from the start of the sort key
1218to the end of the sort key. This argument is optional. If
1219@var{startkeyfun} returns @code{nil} and this argument is omitted (or
1220@code{nil}), then the sort key extends to the end of the record. There
1221is no need for @var{endkeyfun} if @var{startkeyfun} returns a
1222non-@code{nil} value.
1223@end enumerate
1224
1225As an example of @code{sort-subr}, here is the complete function
1226definition for @code{sort-lines}:
1227
1228@example
1229@group
1230;; @r{Note that the first two lines of doc string}
1231;; @r{are effectively one line when viewed by a user.}
1232(defun sort-lines (reverse beg end)
1233 "Sort lines in region alphabetically.
1234Called from a program, there are three arguments:
1235@end group
1236@group
1237REVERSE (non-nil means reverse order),
1238and BEG and END (the region to sort)."
1239 (interactive "P\nr")
1240 (save-restriction
1241 (narrow-to-region beg end)
1242 (goto-char (point-min))
1243 (sort-subr reverse
1244 'forward-line
1245 'end-of-line)))
1246@end group
1247@end example
1248
1249Here @code{forward-line} moves point to the start of the next record,
1250and @code{end-of-line} moves point to the end of record. We do not pass
1251the arguments @var{startkeyfun} and @var{endkeyfun}, because the entire
1252record is used as the sort key.
1253
1254The @code{sort-paragraphs} function is very much the same, except that
1255its @code{sort-subr} call looks like this:
1256
1257@example
1258@group
1259(sort-subr reverse
1260 (function
1261 (lambda ()
1262 (skip-chars-forward "\n \t\f")))
1263 'forward-paragraph)
1264@end group
1265@end example
1266@end defun
1267
1268@deffn Command sort-regexp-fields reverse record-regexp key-regexp start end
1269This command sorts the region between @var{start} and @var{end}
1270alphabetically as specified by @var{record-regexp} and @var{key-regexp}.
1271If @var{reverse} is a negative integer, then sorting is in reverse
1272order.
1273
1274Alphabetical sorting means that two sort keys are compared by
1275comparing the first characters of each, the second characters of each,
1276and so on. If a mismatch is found, it means that the sort keys are
1277unequal; the sort key whose character is less at the point of first
1278mismatch is the lesser sort key. The individual characters are compared
1279according to their numerical values. Since Emacs uses the @sc{ASCII}
1280character set, the ordering in that set determines alphabetical order.
1281@c version 19 change
1282
1283The value of the @var{record-regexp} argument specifies how to divide
1284the buffer into sort records. At the end of each record, a search is
1285done for this regular expression, and the text that matches it is the
1286next record. For example, the regular expression @samp{^.+$}, which
1287matches lines with at least one character besides a newline, would make
1288each such line into a sort record. @xref{Regular Expressions}, for a
1289description of the syntax and meaning of regular expressions.
1290
1291The value of the @var{key-regexp} argument specifies what part of each
1292record is the sort key. The @var{key-regexp} could match the whole
1293record, or only a part. In the latter case, the rest of the record has
1294no effect on the sorted order of records, but it is carried along when
1295the record moves to its new position.
1296
1297The @var{key-regexp} argument can refer to the text matched by a
1298subexpression of @var{record-regexp}, or it can be a regular expression
1299on its own.
1300
1301If @var{key-regexp} is:
1302
1303@table @asis
1304@item @samp{\@var{digit}}
1305then the text matched by the @var{digit}th @samp{\(...\)} parenthesis
1306grouping in @var{record-regexp} is the sort key.
1307
1308@item @samp{\&}
1309then the whole record is the sort key.
1310
1311@item a regular expression
1312then @code{sort-regexp-fields} searches for a match for the regular
1313expression within the record. If such a match is found, it is the sort
1314key. If there is no match for @var{key-regexp} within a record then
1315that record is ignored, which means its position in the buffer is not
1316changed. (The other records may move around it.)
1317@end table
1318
1319For example, if you plan to sort all the lines in the region by the
1320first word on each line starting with the letter @samp{f}, you should
1321set @var{record-regexp} to @samp{^.*$} and set @var{key-regexp} to
1322@samp{\<f\w*\>}. The resulting expression looks like this:
1323
1324@example
1325@group
1326(sort-regexp-fields nil "^.*$" "\\<f\\w*\\>"
1327 (region-beginning)
1328 (region-end))
1329@end group
1330@end example
1331
1332If you call @code{sort-regexp-fields} interactively, it prompts for
1333@var{record-regexp} and @var{key-regexp} in the minibuffer.
1334@end deffn
1335
1336@deffn Command sort-lines reverse start end
1337This command alphabetically sorts lines in the region between
1338@var{start} and @var{end}. If @var{reverse} is non-@code{nil}, the sort
1339is in reverse order.
1340@end deffn
1341
1342@deffn Command sort-paragraphs reverse start end
1343This command alphabetically sorts paragraphs in the region between
1344@var{start} and @var{end}. If @var{reverse} is non-@code{nil}, the sort
1345is in reverse order.
1346@end deffn
1347
1348@deffn Command sort-pages reverse start end
1349This command alphabetically sorts pages in the region between
1350@var{start} and @var{end}. If @var{reverse} is non-@code{nil}, the sort
1351is in reverse order.
1352@end deffn
1353
1354@deffn Command sort-fields field start end
1355This command sorts lines in the region between @var{start} and
1356@var{end}, comparing them alphabetically by the @var{field}th field
1357of each line. Fields are separated by whitespace and numbered starting
1358from 1. If @var{field} is negative, sorting is by the
1359@w{@minus{}@var{field}th} field from the end of the line. This command
1360is useful for sorting tables.
1361@end deffn
1362
1363@deffn Command sort-numeric-fields field start end
1364This command sorts lines in the region between @var{start} and
1365@var{end}, comparing them numerically by the @var{field}th field of each
1366line. The specified field must contain a number in each line of the
1367region. Fields are separated by whitespace and numbered starting from
13681. If @var{field} is negative, sorting is by the
1369@w{@minus{}@var{field}th} field from the end of the line. This command
1370is useful for sorting tables.
1371@end deffn
1372
1373@deffn Command sort-columns reverse &optional beg end
1374This command sorts the lines in the region between @var{beg} and
1375@var{end}, comparing them alphabetically by a certain range of columns.
1376The column positions of @var{beg} and @var{end} bound the range of
1377columns to sort on.
1378
1379If @var{reverse} is non-@code{nil}, the sort is in reverse order.
1380
1381One unusual thing about this command is that the entire line
1382containing position @var{beg}, and the entire line containing position
1383@var{end}, are included in the region sorted.
1384
1385Note that @code{sort-columns} uses the @code{sort} utility program,
1386and so cannot work properly on text containing tab characters. Use
1387@kbd{M-x @code{untabify}} to convert tabs to spaces before sorting.
1388
1389The @code{sort-columns} function did not work on VMS prior to Emacs 19.
1390@end deffn
1391
1392@node Columns
1393@comment node-name, next, previous, up
1394@section Counting Columns
1395@cindex columns
1396@cindex counting columns
1397@cindex horizontal position
1398
1399 The column functions convert between a character position (counting
1400characters from the beginning of the buffer) and a column position
1401(counting screen characters from the beginning of a line).
1402
1403 A character counts according to the number of columns it occupies on
1404the screen. This means control characters count as occupying 2 or 4
1405columns, depending upon the value of @code{ctl-arrow}, and tabs count as
1406occupying a number of columns that depends on the value of
1407@code{tab-width} and on the column where the tab begins. @xref{Usual Display}.
1408
1409 Column number computations ignore the width of the window and the
1410amount of horizontal scrolling. Consequently, a column value can be
1411arbitrarily high. The first (or leftmost) column is numbered 0.
1412
1413@defun current-column
1414This function returns the horizontal position of point, measured in
1415columns, counting from 0 at the left margin. The column position is the
1416sum of the widths of all the displayed representations of the characters
1417between the start of the current line and point.
1418
1419For an example of using @code{current-column}, see the description of
1420@code{count-lines} in @ref{Text Lines}.
1421@end defun
1422
1423@defun move-to-column column &optional force
1424This function moves point to @var{column} in the current line. The
1425calculation of @var{column} takes into account the widths of the
1426displayed representations of the characters between the start of the
1427line and point.
1428
1429If column @var{column} is beyond the end of the line, point moves to the
1430end of the line. If @var{column} is negative, point moves to the
1431beginning of the line.
1432
1433If it is impossible to move to column @var{column} because that is in
1434the middle of a multicolumn character such as a tab, point moves to the
1435end of that character. However, if @var{force} is non-@code{nil}, and
1436@var{column} is in the middle of a tab, then @code{move-to-column}
1437converts the tab into spaces so that it can move precisely to column
1438@var{column}. Other multicolumn characters can cause anomalies despite
1439@var{force}, since there is no way to split them.
1440
1441The argument @var{force} also has an effect if the line isn't long
1442enough to reach column @var{column}; in that case, it says to indent at
1443the end of the line to reach that column.
1444
1445If @var{column} is not an integer, an error is signaled.
1446
1447The return value is the column number actually moved to.
1448@end defun
1449
1450@node Indentation
1451@section Indentation
1452@cindex indentation
1453
1454 The indentation functions are used to examine, move to, and change
1455whitespace that is at the beginning of a line. Some of the functions
1456can also change whitespace elsewhere on a line. Columns and indentation
1457count from zero at the left margin.
1458
1459@menu
1460* Primitive Indent:: Functions used to count and insert indentation.
1461* Mode-Specific Indent:: Customize indentation for different modes.
1462* Region Indent:: Indent all the lines in a region.
1463* Relative Indent:: Indent the current line based on previous lines.
1464* Indent Tabs:: Adjustable, typewriter-like tab stops.
1465* Motion by Indent:: Move to first non-blank character.
1466@end menu
1467
1468@node Primitive Indent
1469@subsection Indentation Primitives
1470
1471 This section describes the primitive functions used to count and
1472insert indentation. The functions in the following sections use these
1473primitives.
1474
1475@defun current-indentation
1476@comment !!Type Primitive Function
1477@comment !!SourceFile indent.c
1478This function returns the indentation of the current line, which is
1479the horizontal position of the first nonblank character. If the
1480contents are entirely blank, then this is the horizontal position of the
1481end of the line.
1482@end defun
1483
1484@deffn Command indent-to column &optional minimum
1485@comment !!Type Primitive Function
1486@comment !!SourceFile indent.c
1487This function indents from point with tabs and spaces until
1488@var{column} is reached. If @var{minimum} is specified and
1489non-@code{nil}, then at least that many spaces are inserted even if this
1490requires going beyond @var{column}. The value is the column at which
1491the inserted indentation ends.
1492@end deffn
1493
1494@defopt indent-tabs-mode
1495@comment !!SourceFile indent.c
1496If this variable is non-@code{nil}, indentation functions can insert
1497tabs as well as spaces. Otherwise, they insert only spaces. Setting
1498this variable automatically makes it local to the current buffer.
1499@end defopt
1500
1501@node Mode-Specific Indent
1502@subsection Indentation Controlled by Major Mode
1503
1504 An important function of each major mode is to customize the @key{TAB}
1505key to indent properly for the language being edited. This section
1506describes the mechanism of the @key{TAB} key and how to control it.
1507The functions in this section return unpredictable values.
1508
1509@defvar indent-line-function
1510This variable's value is the function to be used by @key{TAB} (and
1511various commands) to indent the current line. The command
1512@code{indent-according-to-mode} does no more than call this function.
1513
1514In Lisp mode, the value is the symbol @code{lisp-indent-line}; in C
1515mode, @code{c-indent-line}; in Fortran mode, @code{fortran-indent-line}.
1516In Fundamental mode, Text mode, and many other modes with no standard
1517for indentation, the value is @code{indent-to-left-margin} (which is the
1518default value).
1519@end defvar
1520
1521@deffn Command indent-according-to-mode
1522This command calls the function in @code{indent-line-function} to
1523indent the current line in a way appropriate for the current major mode.
1524@end deffn
1525
1526@deffn Command indent-for-tab-command
1527This command calls the function in @code{indent-line-function} to indent
1528the current line; except that if that function is
1529@code{indent-to-left-margin}, it calls @code{insert-tab} instead. (That
1530is a trivial command which inserts a tab character.)
1531@end deffn
1532
1533@defvar left-margin
1534This variable is the column to which the default
1535@code{indent-line-function} will indent. (That function is
1536@code{indent-to-left-margin}.) In Fundamental mode, @key{LFD} indents
1537to this column. This variable automatically becomes buffer-local when
1538set in any fashion.
1539@end defvar
1540
1541@defun indent-to-left-margin
1542This is the default @code{indent-line-function}, used in Fundamental
1543mode, Text mode, etc. Its effect is to adjust the indentation at the
1544beginning of the current line to the value specified by the variable
1545@code{left-margin}. This may involve either inserting or deleting
1546whitespace.
1547@end defun
1548
1549@deffn Command newline-and-indent
1550@comment !!SourceFile simple.el
1551This function inserts a newline, then indents the new line (the one
1552following the newline just inserted) according to the major mode.
1553
1554It does indentation by calling the current @code{indent-line-function}.
1555In programming language modes, this is the same thing @key{TAB} does,
1556but in some text modes, where @key{TAB} inserts a tab,
1557@code{newline-and-indent} indents to the column specified by
1558@code{left-margin}.
1559@end deffn
1560
1561@deffn Command reindent-then-newline-and-indent
1562@comment !!SourceFile simple.el
1563This command reindents the current line, inserts a newline at point,
1564and then reindents the new line (the one following the newline just
1565inserted).
1566
1567This command does indentation on both lines according to the current
1568major mode, by calling the current value of @code{indent-line-function}.
1569In programming language modes, this is the same thing @key{TAB} does,
1570but in some text modes, where @key{TAB} inserts a tab,
1571@code{reindent-then-newline-and-indent} indents to the column specified
1572by @code{left-margin}.
1573@end deffn
1574
1575@node Region Indent
1576@subsection Indenting an Entire Region
1577
1578 This section describes commands which indent all the lines in the
1579region. They return unpredictable values.
1580
1581@deffn Command indent-region start end to-column
1582This command indents each nonblank line starting between @var{start}
1583(inclusive) and @var{end} (exclusive). If @var{to-column} is
1584@code{nil}, @code{indent-region} indents each nonblank line by calling
1585the current mode's indentation function, the value of
1586@code{indent-line-function}.
1587
1588If @var{to-column} is non-@code{nil}, it should be an integer
1589specifying the number of columns of indentation; then this function
1590gives each line exactly that much indentation, by either adding or
1591deleting whitespace.
1592
1593If there is a fill prefix, @code{indent-region} indents each line
1594by making it start with the fill prefix.
1595@end deffn
1596
1597@defvar indent-region-function
1598The value of this variable is a function that can be used by
1599@code{indent-region} as a short cut. You should design the function so
1600that it will produce the same results as indenting the lines of the
1601region one by one, but presumably faster.
1602
1603If the value is @code{nil}, there is no short cut, and
1604@code{indent-region} actually works line by line.
1605
1606A short cut function is useful in modes such as C mode and Lisp mode,
1607where the @code{indent-line-function} must scan from the beginning of
1608the function: applying it to each line would be quadratic in time. The
1609short cut can update the scan information as it moves through the lines
1610indenting them; this takes linear time. In a mode where indenting a
1611line individually is fast, there is no need for a short cut.
1612
1613@code{indent-region} with a non-@code{nil} argument has a different
1614meaning and does not use this variable.
1615@end defvar
1616
1617@deffn Command indent-rigidly start end count
1618@comment !!SourceFile indent.el
1619This command indents all lines starting between @var{start}
1620(inclusive) and @var{end} (exclusive) sideways by @var{count} columns.
1621This ``preserves the shape'' of the affected region, moving it as a
1622rigid unit. Consequently, this command is useful not only for indenting
1623regions of unindented text, but also for indenting regions of formatted
1624code.
1625
1626For example, if @var{count} is 3, this command adds 3 columns of
1627indentation to each of the lines beginning in the region specified.
1628
1629In Mail mode, @kbd{C-c C-y} (@code{mail-yank-original}) uses
1630@code{indent-rigidly} to indent the text copied from the message being
1631replied to.
1632@end deffn
1633
1634@defun indent-code-rigidly start end columns &optional nochange-regexp
1635This is like @code{indent-rigidly}, except that it doesn't alter lines
1636that start within strings or comments.
1637
1638In addition, it doesn't alter a line if @var{nochange-regexp} matches at
1639the beginning of the line (if @var{nochange-regexp} is non-@code{nil}).
1640@end defun
1641
1642@node Relative Indent
1643@subsection Indentation Relative to Previous Lines
1644
1645 This section describes two commands which indent the current line
1646based on the contents of previous lines.
1647
1648@deffn Command indent-relative &optional unindented-ok
1649This command inserts whitespace at point, extending to the same
1650column as the next @dfn{indent point} of the previous nonblank line. An
1651indent point is a non-whitespace character following whitespace. The
1652next indent point is the first one at a column greater than the current
1653column of point. For example, if point is underneath and to the left of
1654the first non-blank character of a line of text, it moves to that column
1655by inserting whitespace.
1656
1657If the previous nonblank line has no next indent point (i.e., none at a
1658great enough column position), @code{indent-relative} either does
1659nothing (if @var{unindented-ok} is non-@code{nil}) or calls
1660@code{tab-to-tab-stop}. Thus, if point is underneath and to the right
1661of the last column of a short line of text, this command ordinarily
1662moves point to the next tab stop by inserting whitespace.
1663
1664The return value of @code{indent-relative} is unpredictable.
1665
1666In the following example, point is at the beginning of the second
1667line:
1668
1669@example
1670@group
1671 This line is indented twelve spaces.
1672@point{}The quick brown fox jumped.
1673@end group
1674@end example
1675
1676@noindent
1677Evaluation of the expression @code{(indent-relative nil)} produces the
1678following:
1679
1680@example
1681@group
1682 This line is indented twelve spaces.
1683 @point{}The quick brown fox jumped.
1684@end group
1685@end example
1686
1687 In this example, point is between the @samp{m} and @samp{p} of
1688@samp{jumped}:
1689
1690@example
1691@group
1692 This line is indented twelve spaces.
1693The quick brown fox jum@point{}ped.
1694@end group
1695@end example
1696
1697@noindent
1698Evaluation of the expression @code{(indent-relative nil)} produces the
1699following:
1700
1701@example
1702@group
1703 This line is indented twelve spaces.
1704The quick brown fox jum @point{}ped.
1705@end group
1706@end example
1707@end deffn
1708
1709@deffn Command indent-relative-maybe
1710@comment !!SourceFile indent.el
1711This command indents the current line like the previous nonblank line.
1712It calls @code{indent-relative} with @code{t} as the @var{unindented-ok}
1713argument. The return value is unpredictable.
1714
1715If the previous nonblank line has no indent points beyond the current
1716column, this command does nothing.
1717@end deffn
1718
1719@node Indent Tabs
1720@comment node-name, next, previous, up
1721@subsection Adjustable ``Tab Stops''
1722@cindex tabs stops for indentation
1723
1724 This section explains the mechanism for user-specified ``tab stops''
1725and the mechanisms which use and set them. The name ``tab stops'' is
1726used because the feature is similar to that of the tab stops on a
1727typewriter. The feature works by inserting an appropriate number of
1728spaces and tab characters to reach the next tab stop column; it does not
1729affect the display of tab characters in the buffer (@pxref{Usual
1730Display}). Note that the @key{TAB} character as input uses this tab
1731stop feature only in a few major modes, such as Text mode.
1732
1733@deffn Command tab-to-tab-stop
1734This command inserts spaces or tabs up to the next tab stop column
1735defined by @code{tab-stop-list}. It searches the list for an element
1736greater than the current column number, and uses that element as the
1737column to indent to. It does nothing if no such element is found.
1738@end deffn
1739
1740@defopt tab-stop-list
1741This variable is the list of tab stop columns used by
1742@code{tab-to-tab-stops}. The elements should be integers in increasing
1743order. The tab stop columns need not be evenly spaced.
1744
1745Use @kbd{M-x edit-tab-stops} to edit the location of tab stops
1746interactively.
1747@end defopt
1748
1749@node Motion by Indent
1750@subsection Indentation-Based Motion Commands
1751
1752 These commands, primarily for interactive use, act based on the
1753indentation in the text.
1754
1755@deffn Command back-to-indentation
1756@comment !!SourceFile simple.el
1757This command moves point to the first non-whitespace character in the
1758current line (which is the line in which point is located). It returns
1759@code{nil}.
1760@end deffn
1761
1762@deffn Command backward-to-indentation arg
1763@comment !!SourceFile simple.el
1764This command moves point backward @var{arg} lines and then to the
1765first nonblank character on that line. It returns @code{nil}.
1766@end deffn
1767
1768@deffn Command forward-to-indentation arg
1769@comment !!SourceFile simple.el
1770This command moves point forward @var{arg} lines and then to the first
1771nonblank character on that line. It returns @code{nil}.
1772@end deffn
1773
1774@node Case Changes
1775@comment node-name, next, previous, up
1776@section Case Changes
1777@cindex case changes
1778
1779 The case change commands described here work on text in the current
1780buffer. @xref{Character Case}, for case conversion commands that work
1781on strings and characters. @xref{Case Table}, for how to customize
1782which characters are upper or lower case and how to convert them.
1783
1784@deffn Command capitalize-region start end
1785This function capitalizes all words in the region defined by
1786@var{start} and @var{end}. To capitalize means to convert each word's
1787first character to upper case and convert the rest of each word to lower
1788case. The function returns @code{nil}.
1789
1790If one end of the region is in the middle of a word, the part of the
1791word within the region is treated as an entire word.
1792
1793When @code{capitalize-region} is called interactively, @var{start} and
1794@var{end} are point and the mark, with the smallest first.
1795
1796@example
1797@group
1798---------- Buffer: foo ----------
1799This is the contents of the 5th foo.
1800---------- Buffer: foo ----------
1801@end group
1802
1803@group
1804(capitalize-region 1 44)
1805@result{} nil
1806
1807---------- Buffer: foo ----------
1808This Is The Contents Of The 5th Foo.
1809---------- Buffer: foo ----------
1810@end group
1811@end example
1812@end deffn
1813
1814@deffn Command downcase-region start end
1815This function converts all of the letters in the region defined by
1816@var{start} and @var{end} to lower case. The function returns
1817@code{nil}.
1818
1819When @code{downcase-region} is called interactively, @var{start} and
1820@var{end} are point and the mark, with the smallest first.
1821@end deffn
1822
1823@deffn Command upcase-region start end
1824This function converts all of the letters in the region defined by
1825@var{start} and @var{end} to upper case. The function returns
1826@code{nil}.
1827
1828When @code{upcase-region} is called interactively, @var{start} and
1829@var{end} are point and the mark, with the smallest first.
1830@end deffn
1831
1832@deffn Command capitalize-word count
1833This function capitalizes @var{count} words after point, moving point
1834over as it does. To capitalize means to convert each word's first
1835character to upper case and convert the rest of each word to lower case.
1836If @var{count} is negative, the function capitalizes the
1837@minus{}@var{count} previous words but does not move point. The value
1838is @code{nil}.
1839
1840If point is in the middle of a word, the part of word the before point
1841(if moving forward) or after point (if operating backward) is ignored.
1842The rest is treated as an entire word.
1843
1844When @code{capitalize-word} is called interactively, @var{count} is
1845set to the numeric prefix argument.
1846@end deffn
1847
1848@deffn Command downcase-word count
1849This function converts the @var{count} words after point to all lower
1850case, moving point over as it does. If @var{count} is negative, it
1851converts the @minus{}@var{count} previous words but does not move point.
1852The value is @code{nil}.
1853
1854When @code{downcase-word} is called interactively, @var{count} is set
1855to the numeric prefix argument.
1856@end deffn
1857
1858@deffn Command upcase-word count
1859This function converts the @var{count} words after point to all upper
1860case, moving point over as it does. If @var{count} is negative, it
1861converts the @minus{}@var{count} previous words but does not move point.
1862The value is @code{nil}.
1863
1864When @code{upcase-word} is called interactively, @var{count} is set to
1865the numeric prefix argument.
1866@end deffn
1867
1868@node Text Properties
1869@section Text Properties
1870@cindex text properties
1871@cindex attributes of text
1872@cindex properties of text
1873
1874 Each character position in a buffer or a string can have a @dfn{text
1875property list}, much like the property list of a symbol (@pxref{Property
1876Lists}). The properties belong to a particular character at a
1877particular place, such as, the letter @samp{T} at the beginning of this
1878sentence or the first @samp{o} in @samp{foo}---if the same character
1879occurs in two different places, the two occurrences generally have
1880different properties.
1881
1882 Each property has a name and a value. Both of these can be any Lisp
1883object, but the name is normally a symbol. The usual way to access the
1884property list is to specify a name and ask what value corresponds to it.
1885
1886 If a character has a @code{category} property, we call it the
1887@dfn{category} of the character. It should be a symbol. The properties
1888of the symbol serve as defaults for the properties of the character.
1889
1890 Copying text between strings and buffers preserves the properties
1891along with the characters; this includes such diverse functions as
1892@code{substring}, @code{insert}, and @code{buffer-substring}.
1893
1894@menu
1895* Examining Properties:: Looking at the properties of one character.
1896* Changing Properties:: Setting the properties of a range of text.
1897* Property Search:: Searching for where a property changes value.
1898* Special Properties:: Particular properties with special meanings.
1899* Sticky Properties:: How inserted text gets properties from
1900 neighboring text.
1901* Saving Properties:: Saving text properties in files, and reading
1902 them back.
1903* Not Intervals:: Why text properties do not use
1904 Lisp-visible text intervals.
1905@end menu
1906
1907@node Examining Properties
1908@subsection Examining Text Properties
1909
1910 The simplest way to examine text properties is to ask for the value of
1911a particular property of a particular character. For that, use
1912@code{get-text-property}. Use @code{text-properties-at} to get the
1913entire property list of a character. @xref{Property Search}, for
1914functions to examine the properties of a number of characters at once.
1915
1916 These functions handle both strings and buffers. Keep in mind that
1917positions in a string start from 0, whereas positions in a buffer start
1918from 1.
1919
1920@defun get-text-property pos prop &optional object
1921This function returns the value of the @var{prop} property of the
1922character after position @var{pos} in @var{object} (a buffer or
1923string). The argument @var{object} is optional and defaults to the
1924current buffer.
1925
1926If there is no @var{prop} property strictly speaking, but the character
1927has a category which is a symbol, then @code{get-text-property} returns
1928the @var{prop} property of that symbol.
1929@end defun
1930
1931@defun get-char-property pos prop &optional object
1932This function is like @code{get-text-property}, except that it checks
1933overlays first and then text properties. @xref{Overlays}.
1934
1935The argument @var{object} may be a string, a buffer, or a window. If it
1936is a window, then the buffer displayed in that window is used for text
1937properties and overlays, but only the overlays active for that window
1938are considered. If @var{object} is a buffer, then all overlays in that
1939buffer are considered, as well as text properties. If @var{object} is a
1940string, only text properties are considered, since strings never have
1941overlays.
1942@end defun
1943
1944@defun text-properties-at position &optional object
1945This function returns the entire property list of the character at
1946@var{position} in the string or buffer @var{object}. If @var{object} is
1947@code{nil}, it defaults to the current buffer.
1948@end defun
1949
1950@node Changing Properties
1951@subsection Changing Text Properties
1952
1953 The primitives for changing properties apply to a specified range of
1954text. The function @code{set-text-properties} (see end of section) sets
1955the entire property list of the text in that range; more often, it is
1956useful to add, change, or delete just certain properties specified by
1957name.
1958
1959 Since text properties are considered part of the buffer's contents, and
1960can affect how the buffer looks on the screen, any change in the text
1961properties is considered a buffer modification. Buffer text property
1962changes are undoable (@pxref{Undo}).
1963
1964@defun add-text-properties start end props &optional object
1965This function modifies the text properties for the text between
1966@var{start} and @var{end} in the string or buffer @var{object}. If
1967@var{object} is @code{nil}, it defaults to the current buffer.
1968
1969The argument @var{props} specifies which properties to change. It
1970should have the form of a property list (@pxref{Property Lists}): a list
1971whose elements include the property names followed alternately by the
1972corresponding values.
1973
1974The return value is @code{t} if the function actually changed some
1975property's value; @code{nil} otherwise (if @var{props} is @code{nil} or
1976its values agree with those in the text).
1977
1978For example, here is how to set the @code{comment} and @code{face}
1979properties of a range of text:
1980
1981@example
1982(add-text-properties @var{start} @var{end}
1983 '(comment t face highlight))
1984@end example
1985@end defun
1986
1987@defun put-text-property start end prop value &optional object
1988This function sets the @var{prop} property to @var{value} for the text
1989between @var{start} and @var{end} in the string or buffer @var{object}.
1990If @var{object} is @code{nil}, it defaults to the current buffer.
1991@end defun
1992
1993@defun remove-text-properties start end props &optional object
1994This function deletes specified text properties from the text between
1995@var{start} and @var{end} in the string or buffer @var{object}. If
1996@var{object} is @code{nil}, it defaults to the current buffer.
1997
1998The argument @var{props} specifies which properties to delete. It
1999should have the form of a property list (@pxref{Property Lists}): a list
2000whose elements are property names alternating with corresponding values.
2001But only the names matter---the values that accompany them are ignored.
2002For example, here's how to remove the @code{face} property.
2003
2004@example
2005(remove-text-properties @var{start} @var{end} '(face nil))
2006@end example
2007
2008The return value is @code{t} if the function actually changed some
2009property's value; @code{nil} otherwise (if @var{props} is @code{nil} or
2010if no character in the specified text had any of those properties).
2011@end defun
2012
2013@defun set-text-properties start end props &optional object
2014This function completely replaces the text property list for the text
2015between @var{start} and @var{end} in the string or buffer @var{object}.
2016If @var{object} is @code{nil}, it defaults to the current buffer.
2017
2018The argument @var{props} is the new property list. It should be a list
2019whose elements are property names alternating with corresponding values.
2020
2021After @code{set-text-properties} returns, all the characters in the
2022specified range have identical properties.
2023
2024If @var{props} is @code{nil}, the effect is to get rid of all properties
2025from the specified range of text. Here's an example:
2026
2027@example
2028(set-text-properties @var{start} @var{end} nil)
2029@end example
2030@end defun
2031
2032@node Property Search
2033@subsection Property Search Functions
2034
2035In typical use of text properties, most of the time several or many
2036consecutive characters have the same value for a property. Rather than
2037writing your programs to examine characters one by one, it is much
2038faster to process chunks of text that have the same property value.
2039
2040Here are functions you can use to do this. In all cases, @var{object}
2041defaults to the current buffer.
2042
2043For high performance, it's very important to use the @var{limit}
2044argument to these functions, especially the ones that search for a
2045single property---otherwise, they may spend a long time considering
2046changes in other properties while scanning to the end of the buffer.
2047
2048@defun next-property-change pos &optional object limit
2049The function scans the text forward from position @var{pos} in the
2050string or buffer @var{object} till it finds a change in some text
2051property, then returns the position of the change. In other words, it
2052returns the position of the first character beyond @var{pos} whose
2053properties are not identical to those of the character just after
2054@var{pos}.
2055
2056If @var{limit} is non-@code{nil}, then the scan ends at position
2057@var{limit}. If there is no property change before that point,
2058@code{next-property-change} returns @var{limit}.
2059
2060The value is @code{nil} if the properties remain unchanged all the way
2061to the end of @var{object} and @var{limit} is @code{nil}.
2062
2063If the value is non-@code{nil}, it is a position greater than or equal
2064to @var{pos}. The value equals @var{pos} only when @var{limit} equals
2065@var{pos}.
2066
2067Here is an example of how to scan the buffer by chunks of text within
2068which all properties are constant:
2069
2070@smallexample
2071(while (not (eobp))
2072 (let ((plist (text-properties-at (point)))
2073 (next-change
2074 (or (next-property-change (point) (current-buffer))
2075 (point-max))))
2076 @r{Process text from point to @var{next-change}@dots{}}
2077 (goto-char next-change)))
2078@end smallexample
2079@end defun
2080
2081@defun next-single-property-change pos prop &optional object limit
2082The function scans the text forward from position @var{pos} in the
2083string or buffer @var{object} till it finds a change in the @var{prop}
2084property, then returns the position of the change. In other words, it
2085returns the position of the first character beyond @var{pos} whose
2086@var{prop} property differs from that of the character just after
2087@var{pos}.
2088
2089If @var{limit} is non-@code{nil}, then the scan ends at position
2090@var{limit}. If there is no property change before that point,
2091@code{next-single-property-change} returns @var{limit}.
2092
2093The value is @code{nil} if the property remains unchanged all the way to
2094the end of @var{object} and @var{limit} is @code{nil}. If the value is
2095non-@code{nil}, it is a position greater than or equal to @var{pos}; it
2096equals @var{pos} only if @var{limit} equals @var{pos}.
2097@end defun
2098
2099@defun previous-property-change pos &optional object limit
2100This is like @code{next-property-change}, but scans back from @var{pos}
2101instead of forward. If the value is non-@code{nil}, it is a position
2102less than or equal to @var{pos}; it equals @var{pos} only if @var{limit}
2103equals @var{pos}.
2104
2105Remember that a position is always between two characters; the position
2106returned by this function is between two characters with different
2107properties.
2108@end defun
2109
2110@defun previous-single-property-change pos prop &optional object limit
2111This is like @code{next-property-change}, but scans back from @var{pos}
2112instead of forward. If the value is non-@code{nil}, it is a position
2113less than or equal to @var{pos}; it equals @var{pos} only if @var{limit}
2114equals @var{pos}.
2115@end defun
2116
2117@defun text-property-any start end prop value &optional object
2118This function returns non-@code{nil} if at least one character between
2119@var{start} and @var{end} has a property @var{prop} whose value is
2120@var{value}. More precisely, it returns the position of the first such
2121character. Otherwise, it returns @code{nil}.
2122
2123The optional fifth argument, @var{object}, specifies the string or
2124buffer to scan. Positions are relative to @var{object}. The default
2125for @var{object} is the current buffer.
2126@end defun
2127
2128@defun text-property-not-all start end prop value &optional object
2129This function returns non-@code{nil} if at least one character between
2130@var{start} and @var{end} has a property @var{prop} whose value differs
2131from @var{value}. More precisely, it returns the position of the
2132first such character. Otherwise, it returns @code{nil}.
2133
2134The optional fifth argument, @var{object}, specifies the string or
2135buffer to scan. Positions are relative to @var{object}. The default
2136for @var{object} is the current buffer.
2137@end defun
2138
2139@node Special Properties
2140@subsection Properties with Special Meanings
2141
2142@table @code
2143@cindex category of text character
2144@kindex category @r{(text property)}
2145@item category
2146If a character has a @code{category} property, we call it the
2147@dfn{category} of the character. It should be a symbol. The properties
2148of the symbol serve as defaults for the properties of the character.
2149
2150@item face
2151@cindex face codes of text
2152@kindex face @r{(text property)}
2153You can use the property @code{face} to control the font and color of
2154text. @xref{Faces}, for more information. This feature is temporary;
2155in the future, we may replace it with other ways of specifying how to
2156display text.
2157
2158@item mouse-face
2159@kindex mouse-face @r{(text property)}
2160The property @code{mouse-face} is used instead of @code{face} when the
2161mouse is on or near the character. For this purpose, ``near'' means
2162that all text between the character and where the mouse is have the same
2163@code{mouse-face} property value.
2164
2165@item local-map
2166@cindex keymap of character
2167@kindex local-map @r{(text property)}
2168You can specify a different keymap for a portion of the text by means
2169of a @code{local-map} property. The property's value, for the character
2170after point, replaces the buffer's local map. @xref{Active Keymaps}.
2171
2172@item read-only
2173@cindex read-only character
2174@kindex read-only @r{(text property)}
2175If a character has the property @code{read-only}, then modifying that
2176character is not allowed. Any command that would do so gets an error.
2177
2178Insertion next to a read-only character is an error if inserting
2179ordinary text there would inherit the @code{read-only} property due to
2180stickiness. Thus, you can control permission to insert next to
2181read-only text by controlling the stickiness. @xref{Sticky Properties}.
2182
2183Since changing properties counts as modifying the buffer, it is not
2184possible to remove a @code{read-only} property unless you know the
2185special trick: bind @code{inhibit-read-only} to a non-@code{nil} value
2186and then remove the property. @xref{Read Only Buffers}.
2187
2188@item invisible
2189@kindex invisible @r{(text property)}
2190A non-@code{nil} @code{invisible} property means a character does not
2191appear on the screen. This works much like selective display. Details
2192of this feature are likely to change in future versions, so check the
2193@file{etc/NEWS} file in the version you are using.
2194
2195@item modification-hooks
2196@cindex change hooks for a character
2197@cindex hooks for changing a character
2198@kindex modification-hooks @r{(text property)}
2199If a character has the property @code{modification-hooks}, then its
2200value should be a list of functions; modifying that character calls all
2201of those functions. Each function receives two arguments: the beginning
2202and end of the part of the buffer being modified. Note that if a
2203particular modification hook function appears on several characters
2204being modified by a single primitive, you can't predict how many times
2205the function will be called.
2206
2207@item insert-in-front-hooks
2208@itemx insert-behind-hooks
2209@kindex insert-in-front-hooks @r{(text property)}
2210@kindex insert-behind-hooks @r{(text property)}
2211Assuming insertion is allowed, it then calls the functions
2212listed in the @code{insert-in-front-hooks} property of the following
2213character and in the @code{insert-behind-hooks} property of the
2214preceding character. These functions receive two arguments, the
2215beginning and end of the inserted text.
2216
2217See also @ref{Change Hooks}, for other hooks that are called
2218when you change text in a buffer.
2219
2220@item point-entered
2221@itemx point-left
2222@cindex hooks for motion of point
2223@kindex point-entered @r{(text property)}
2224@kindex point-left @r{(text property)}
2225The special properties @code{point-entered} and @code{point-left}
2226record hook functions that report motion of point. Each time point
2227moves, Emacs compares these two property values:
2228
2229@itemize @bullet
2230@item
2231the @code{point-left} property of the character after the old location,
2232and
2233@item
2234the @code{point-entered} property of the character after the new
2235location.
2236@end itemize
2237
2238@noindent
2239If these two values differ, each of them is called (if not @code{nil})
2240with two arguments: the old value of point, and the new one.
2241
2242The same comparison is made for the characters before the old and new
2243locations. The result may be to execute two @code{point-left} functions
2244(which may be the same function) and/or two @code{point-entered}
2245functions (which may be the same function). The @code{point-left}
2246functions are always called before the @code{point-entered} functions.
2247
2248A primitive function may examine characters at various positions
2249without moving point to those positions. Only an actual change in the
2250value of point runs these hook functions.
2251@end table
2252
2253@defvar inhibit-point-motion-hooks
2254When this variable is non-@code{nil}, @code{point-left} and
2255@code{point-entered} hooks are not run.
2256@end defvar
2257
2258@node Sticky Properties
2259@subsection Stickiness of Text Properties
2260@cindex sticky text properties
2261@cindex inheritance of text properties
2262
2263 Self-inserting characters normally take on the same properties as the
2264preceding character. This is called @dfn{inheritance} of properties.
2265
2266 In a Lisp program, you can do insertion with inheritance or without,
2267depending on your choice of insertion primitive. The ordinary text
2268insertion functions such as @code{insert} do not inherit any properties.
2269They insert text with precisely the properties of the string being
2270inserted, and no others. This is correct for programs that copy text
2271from one context to another---for example, into or out of the kill
2272ring. To insert with inheritance, use the special primatives described
2273in this section.
2274
2275 When you do insertion with inheritance, @emph{which} properties are
2276inherited depends on two specific properties: @code{front-sticky} and
2277@code{rear-nonsticky}.
2278
2279 Insertion after a character inherits those of its properties that are
2280@dfn{rear-sticky}. Insertion before a character inherits those of its
2281properties that are @dfn{front-sticky}. By default, a text property is
2282rear-sticky but not front-sticky. Thus, the default is to inherit all
2283the properties of the preceding character, and nothing from the
2284following character. You can request different behavior by specifying
2285the stickiness of certain properties.
2286
2287 If a character's @code{front-sticky} property is @code{t}, then all
2288its properties are front-sticky. If the @code{front-sticky} property is
2289a list, then the sticky properties of the character are those whose
2290names are in the list. For example, if a character has a
2291@code{front-sticky} property whose value is @code{(face read-only)},
2292then insertion before the character can inherit its @code{face} property
2293and its @code{read-only} property, but no others.
2294
2295 The @code{rear-nonsticky} works the opposite way. Every property is
2296rear-sticky by default, so the @code{rear-nonsticky} property says which
2297properties are @emph{not} rear-sticky. If a character's
2298@code{rear-nonsticky} property is @code{t}, then none of its properties
2299are rear-sticky. If the @code{rear-nonsticky} property is a list,
2300properties are rear-sticky @emph{unless} their names are in the list.
2301
2302 When you insert text with inheritance, it inherits all the rear-sticky
2303properties of the preceding character, and all the front-sticky
2304properties of the following character. The previous character's
2305properties take precedence when both sides offer different sticky values
2306for the same property.
2307
2308 Here are the functions that insert text with inheritance of properties:
2309
2310@defun insert-and-inherit &rest strings
2311Insert the strings @var{strings}, just like the function @code{insert},
2312but inherit any sticky properties from the adjoining text.
2313@end defun
2314
2315@defun insert-before-markers-and-inherit &rest strings
2316Insert the strings @var{strings}, just like the function
2317@code{insert-before-markers}, but inherit any sticky properties from the
2318adjoining text.
2319@end defun
2320
2321@node Saving Properties
2322@subsection Saving Text Properites in Files
2323@cindex text properties in files
2324@cindex saving text properties
2325
2326 You can save text properties in files, and restore text properties
2327when inserting the files, using these two hooks:
2328
2329@defvar write-region-annotation-functions
2330This variable's value is a list of functions for @code{write-region} to
2331run to encode text properties in some fashion as annotations to the text
2332being written in the file. @xref{Writing to Files}.
2333
2334Each function in the list is called with two arguments: the start and
2335end of the region to be written. These functions should not alter the
2336contents of the buffer. Instead, they should return lists indicating
2337annotations to write in the file in addition to the text in the
2338buffer.
2339
2340Each function should return a list of elements of the form
2341@code{(@var{position} . @var{string})}, where @var{position} is an
2342integer specifying the relative position in the text to be written, and
2343@var{string} is the annotation to add there.
2344
2345Each list returned by one of these functions must be already sorted in
2346increasing order by @var{position}. If there is more than one function,
2347@code{write-region} merges the lists destructively into one sorted list.
2348
2349When @code{write-region} actually writes the text from the buffer to the
2350file, it intermixes the specified annotations at the corresponding
2351positions. All this takes place without modifying the buffer.
2352@end defvar
2353
2354@defvar after-insert-file-functions
2355This variable holds a list of functions for @code{insert-file-contents}
2356to call after inserting a file's contents. These functions should scan
2357the inserted text for annotations, and convert them to the text
2358properties they stand for.
2359
2360Each function receives one argument, the length of the inserted text;
2361point indicates the start of that text. The function should scan that
2362text for annotations, delete them, and create the text properties that
2363the annotations specify. The function should return the updated length
2364of the inserted text, as it stands after those changes. The value
2365returned by one function becomes the argument to the next function.
2366
2367These functions should always return with point at the beginning of
2368the inserted text.
2369
2370The intended use of @code{after-insert-file-functions} is for converting
2371some sort of textual annotations into actual text properties. But other
2372uses may be possible.
2373@end defvar
2374
2375We invite users to write Lisp programs to store and retrieve text
2376properties in files, using these hooks, and thus to experiment with
2377various data formats and find good ones. Eventually we hope users
2378will produce good, general extensions we can install in Emacs.
2379
2380We suggest not trying to handle arbitrary Lisp objects as property
2381names or property values---because a program that general is probably
2382difficult to write, and slow. Instead, choose a set of possible data
2383types that are reasonably flexible, and not too hard to encode.
2384
2385@node Not Intervals
2386@subsection Why Text Properties are not Intervals
2387@cindex intervals
2388
2389 Some editors that support adding attributes to text in the buffer do
2390so by letting the user specify ``intervals'' within the text, and adding
2391the properties to the intervals. Those editors permit the user or the
2392programmer to determine where individual intervals start and end. We
2393deliberately provided a different sort of interface in Emacs Lisp to
2394avoid certain paradoxical behavior associated with text modification.
2395
2396 If the actual subdivision into intervals is meaningful, that means you
2397can distinguish between a buffer that is just one interval with a
2398certain property, and a buffer containing the same text subdivided into
2399two intervals, both of which have that property.
2400
2401 Suppose you take the buffer with just one interval and kill part of
2402the text. The text remaining in the buffer is one interval, and the
2403copy in the kill ring (and the undo list) becomes a separate interval.
2404Then if you yank back the killed text, you get two intervals with the
2405same properties. Thus, editing does not preserve the distinction
2406between one interval and two.
2407
2408 Suppose we ``fix'' this problem by coalescing the two intervals when
2409the text is inserted. That works fine if the buffer originally was a
2410single interval. But suppose instead that we have two adjacent
2411intervals with the same properties, and we kill the text of one interval
2412and yank it back. The same interval-coalescence feature that rescues
2413the other case causes trouble in this one: after yanking, we have just
2414one interval. One again, editing does not preserve the distinction
2415between one interval and two.
2416
2417 Insertion of text at the border between intervals also raises
2418questions that have no satisfactory answer.
2419
2420 However, it is easy to arrange for editing to behave consistently for
2421questions of the form, ``What are the properties of this character?''
2422So we have decided these are the only questions that make sense; we have
2423not implemented asking questions about where intervals start or end.
2424
2425 In practice, you can usually use the property search functions in
2426place of explicit interval boundaries. You can think of them as finding
2427the boundaries of intervals, assuming that intervals are always
2428coalesced whenever possible. @xref{Property Search}.
2429
2430 Emacs also provides explicit intervals as a presentation feature; see
2431@ref{Overlays}.
2432
2433@node Substitution
2434@section Substituting for a Character Code
2435
2436 The following functions replace characters within a specified region
2437based on their character codes.
2438
2439@defun subst-char-in-region start end old-char new-char &optional noundo
2440@cindex replace characters
2441This function replaces all occurrences of the character @var{old-char}
2442with the character @var{new-char} in the region of the current buffer
2443defined by @var{start} and @var{end}.
2444
2445@cindex Outline mode
2446@cindex undo avoidance
2447If @var{noundo} is non-@code{nil}, then @code{subst-char-in-region}
2448does not record the change for undo and does not mark the buffer as
2449modified. This feature is useful for changes which are not considered
2450significant, such as when Outline mode changes visible lines to
2451invisible lines and vice versa.
2452
2453@code{subst-char-in-region} does not move point and returns
2454@code{nil}.
2455
2456@example
2457@group
2458---------- Buffer: foo ----------
2459This is the contents of the buffer before.
2460---------- Buffer: foo ----------
2461@end group
2462
2463@group
2464(subst-char-in-region 1 20 ?i ?X)
2465 @result{} nil
2466
2467---------- Buffer: foo ----------
2468ThXs Xs the contents of the buffer before.
2469---------- Buffer: foo ----------
2470@end group
2471@end example
2472@end defun
2473
2474@defun translate-region start end table
2475This function applies a translation table to the characters in the
2476buffer between positions @var{start} and @var{end}.
2477
2478The translation table @var{table} is a string; @code{(aref @var{table}
2479@var{ochar})} gives the translated character corresponding to
2480@var{ochar}. If the length of @var{table} is less than 256, any
2481characters with codes larger than the length of @var{table} are not
2482altered by the translation.
2483
2484The return value of @code{translate-region} is the number of
2485characters which were actually changed by the translation. This does
2486not count characters which were mapped into themselves in the
2487translation table.
2488
2489This function is available in Emacs versions 19 and later.
2490@end defun
2491
2492@node Registers
2493@section Registers
2494@cindex registers
2495
2496 A register is a sort of variable used in Emacs editing that can hold a
2497marker, a string, a rectangle, a window configuration (of one frame), or
2498a frame configuration (of all frames). Each register is named by a
2499single character. All characters, including control and meta characters
2500(but with the exception of @kbd{C-g}), can be used to name registers.
2501Thus, there are 255 possible registers. A register is designated in
2502Emacs Lisp by a character which is its name.
2503
2504 The functions in this section return unpredictable values unless
2505otherwise stated.
2506@c Will change in version 19
2507
2508@defvar register-alist
2509This variable is an alist of elements of the form @code{(@var{name} .
2510@var{contents})}. Normally, there is one element for each Emacs
2511register that has been used.
2512
2513The object @var{name} is a character (an integer) identifying the
2514register. The object @var{contents} is a string, marker, or list
2515representing the register contents. A string represents text stored in
2516the register. A marker represents a position. A list represents a
2517rectangle; its elements are strings, one per line of the rectangle.
2518@end defvar
2519
2520@defun get-register reg
2521This function returns the contents of the register
2522@var{reg}, or @code{nil} if it has no contents.
2523@end defun
2524
2525@defun set-register reg value
2526This function sets the contents of register @var{reg} to @var{value}.
2527A register can be set to any value, but the other register functions
2528expect only certain data types. The return value is @var{value}.
2529@end defun
2530
2531@deffn Command view-register reg
2532This command displays what is contained in register @var{reg}.
2533@end deffn
2534
2535@ignore
2536@deffn Command point-to-register reg
2537This command stores both the current location of point and the current
2538buffer in register @var{reg} as a marker.
2539@end deffn
2540
2541@deffn Command jump-to-register reg
2542@deffnx Command register-to-point reg
2543@comment !!SourceFile register.el
2544This command restores the status recorded in register @var{reg}.
2545
2546If @var{reg} contains a marker, it moves point to the position stored in
2547the marker. Since both the buffer and the location within the buffer
2548are stored by the @code{point-to-register} function, this command can
2549switch you to another buffer.
2550
2551If @var{reg} contains a window configuration or a frame configuration.
2552@code{jump-to-register} restores that configuration.
2553@end deffn
2554@end ignore
2555
2556@deffn Command insert-register reg &optional beforep
2557This command inserts contents of register @var{reg} into the current
2558buffer.
2559
2560Normally, this command puts point before the inserted text, and the
2561mark after it. However, if the optional second argument @var{beforep}
2562is non-@code{nil}, it puts the mark before and point after.
2563You can pass a non-@code{nil} second argument @var{beforep} to this
2564function interactively by supplying any prefix argument.
2565
2566If the register contains a rectangle, then the rectangle is inserted
2567with its upper left corner at point. This means that text is inserted
2568in the current line and underneath it on successive lines.
2569
2570If the register contains something other than saved text (a string) or
2571a rectangle (a list), currently useless things happen. This may be
2572changed in the future.
2573@end deffn
2574
2575@ignore
2576@deffn Command copy-to-register reg start end &optional delete-flag
2577This command copies the region from @var{start} to @var{end} into
2578register @var{reg}. If @var{delete-flag} is non-@code{nil}, it deletes
2579the region from the buffer after copying it into the register.
2580@end deffn
2581
2582@deffn Command prepend-to-register reg start end &optional delete-flag
2583This command prepends the region from @var{start} to @var{end} into
2584register @var{reg}. If @var{delete-flag} is non-@code{nil}, it deletes
2585the region from the buffer after copying it to the register.
2586@end deffn
2587
2588@deffn Command append-to-register reg start end &optional delete-flag
2589This command appends the region from @var{start} to @var{end} to the
2590text already in register @var{reg}. If @var{delete-flag} is
2591non-@code{nil}, it deletes the region from the buffer after copying it
2592to the register.
2593@end deffn
2594
2595@deffn Command copy-rectangle-to-register reg start end &optional delete-flag
2596This command copies a rectangular region from @var{start} to @var{end}
2597into register @var{reg}. If @var{delete-flag} is non-@code{nil}, it
2598deletes the region from the buffer after copying it to the register.
2599@end deffn
2600
2601@deffn Command window-configuration-to-register reg
2602This function stores the window configuration of the selected frame in
2603register @var{reg}.
2604@end deffn
2605
2606@deffn Command frame-configuration-to-register reg
2607This function stores the current frame configuration in register
2608@var{reg}.
2609@end deffn
2610@end ignore
2611
2612@node Change Hooks
2613@section Change Hooks
2614@cindex change hooks
2615@cindex hooks for text changes
2616
2617 These hook variables let you arrange to take notice of all changes in
2618all buffers (or in a particular buffer, if you make them buffer-local).
2619See also @ref{Special Properties}, for how to detect changes to specific
2620parts of the text.
2621
2622 The functions you use in these hooks should save and restore the match
2623data if they do anything that uses regular expressions; otherwise, they
2624will interfere in bizarre ways with the editing operations that call
2625them.
2626
2627@defvar before-change-function
2628If this variable is non-@code{nil}, then it should be a function; the
2629function is called before any buffer modification. Its arguments are
2630the beginning and end of the region that is about to change,
2631represented as integers. The buffer that is about to change is always
2632the current buffer.
2633@end defvar
2634
2635@defvar after-change-function
2636If this variable is non-@code{nil}, then it should be a function; the
2637function is called after any buffer modification. It receives three
2638arguments: the beginning and end of the region just changed, and the
2639length of the text that existed before the change. (To get the
2640current length, subtract the region beginning from the region end.)
2641All three arguments are integers. The buffer that's about to change
2642is always the current buffer.
2643@end defvar
2644
2645Both of these variables are temporarily bound to @code{nil} during the
2646time that either of these hooks is running. This means that if one of
2647these functions changes the buffer, that change won't run these
2648functions. If you do want the hook function to run recursively,
2649design your hook functions to bind these variables back to their usual
2650values.
2651
2652@defvar first-change-hook
2653This variable is a normal hook that is run whenever a buffer is changed
2654that was previously in the unmodified state.
2655@end defvar
2656
2657 The variables described in this section are meaningful only starting
2658with Emacs version 19.