diff options
author | Richard M. Stallman <rms@gnu.org> | 1994-03-28 20:21:44 +0000 |
---|---|---|
committer | Richard M. Stallman <rms@gnu.org> | 1994-03-28 20:21:44 +0000 |
commit | 3817a596791bc4da72af93659fcb1f0a2ef817bc (patch) | |
tree | f13bd5d740d6a0abeaf7642b7766364cc50bb28e | |
parent | 7fa94aae1b5922e037ebf3be6fb03c09c3fe422b (diff) | |
download | emacs-3817a596791bc4da72af93659fcb1f0a2ef817bc.tar.gz |
Initial revision
-rw-r--r-- | lispref/Makefile.in | 120 | ||||
-rw-r--r-- | lispref/debugging.texi | 701 | ||||
-rw-r--r-- | lispref/edebug.texi | 1676 | ||||
-rw-r--r-- | lispref/eval.texi | 695 | ||||
-rw-r--r-- | lispref/keymaps.texi | 1638 | ||||
-rw-r--r-- | lispref/lists.texi | 1384 | ||||
-rw-r--r-- | lispref/macros.texi | 593 | ||||
-rw-r--r-- | lispref/os.texi | 1355 | ||||
-rw-r--r-- | lispref/processes.texi | 1139 | ||||
-rw-r--r-- | lispref/text.texi | 2658 |
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 @@ +# Makefile for the GNU Emacs Lisp Reference Manual. +# +# 11 August 1990 + +# Redefine `TEX' if `tex' does not invoke plain TeX. For example: +# TEX=platex + +TEX=tex + +# Where the TeX macros are kept: +texmacrodir = /usr/local/lib/tex/macros + +# Where the Emacs hierarchy lives ($EMACS in the INSTALL document for Emacs.) +# For example: +# emacslibdir = /usr/local/gnu/lib/emacs + +# Directory where Emacs is installed, by default: +emacslibdir = /usr/local/emacs + +# Unless you have a nonstandard Emacs installation, these shouldn't have to +# be changed. +prefix = /usr/local +infodir = ${prefix}/info + +# The name of the manual: + +VERSION=2.02.2 +manual = elisp-manual-19-$(VERSION) + +# Uncomment this line for permuted index. +# permuted_index = 1 + +# List of all the texinfo files in the manual: + +srcs = elisp.texi back.texi \ + abbrevs.texi anti.texi backups.texi locals.texi buffers.texi \ + calendar.texi commands.texi compile.texi control.texi debugging.texi \ + display.texi edebug.texi errors.texi eval.texi files.texi \ + frames.texi functions.texi help.texi hooks.texi \ + internals.texi intro.texi keymaps.texi lists.texi \ + loading.texi macros.texi maps.texi markers.texi \ + minibuf.texi modes.texi numbers.texi objects.texi \ + os.texi positions.texi processes.texi searching.texi \ + sequences.texi streams.texi strings.texi symbols.texi \ + syntax.texi text.texi tips.texi variables.texi \ + windows.texi \ + index.unperm index.perm + +.PHONY: elisp.dvi clean + +elisp.dvi: $(srcs) index.texi texindex + # Avoid losing old contents of aux file entirely. + -mv elisp.aux elisp.oaux + # First shot to define xrefs: + $(TEX) elisp.texi + if [ a${permuted_index} != a ]; \ + then \ + ./permute-index; \ + mv permuted.fns elisp.fns; \ + else \ + ./texindex elisp.??; \ + fi + $(TEX) elisp.texi + +index.texi: + if [ a${permuted_index} != a ]; \ + then \ + ln -s index.perm index.texi; \ + else \ + ln -s index.unperm index.texi; \ + fi + +# The info file is named `elisp'. + +elisp: $(srcs) index.texi makeinfo + ./makeinfo elisp.texi + +install: elisp elisp.dvi + mv elisp elisp-* $(infodir) + @echo also add the line for elisp to $(infodir)/dir. + +installall: install + install -c texinfo.tex $(texmacrodir) + +clean: + rm -f *.toc *.aux *.log *.cp *.cps *.fn *.fns *.tp *.tps \ + *.vr *.vrs *.pg *.pgs *.ky *.kys + rm -f make.out core + rm -f makeinfo.o makeinfo getopt.o getopt1.o + rm -f texindex.o texindex index.texi + +dist: + -mkdir temp + -mkdir temp/$(manual) + -ln README Makefile permute-index $(srcs) \ + texinfo.tex getopt.c getopt1.c getopt.h \ + elisp.dvi elisp.aux elisp.??s elisp elisp-[0-9] elisp-[0-9][0-9] temp/$(manual) + -rm -f temp/$(manual)/texindex.c temp/$(manual)/makeinfo.c + cp texindex.c makeinfo.c temp/$(manual) + (cd temp/$(manual); rm -f *~) + (cd temp; tar chf - $(manual)) | gzip > $(manual).tar.gz + -rm -rf temp + +# Make two programs used in generating output from texinfo. + +CFLAGS = -g + +texindex: texindex.o + $(CC) -o $@ $(LDFLAGS) $(CFLAGS) $? +texindex.o: texindex.c + +MAKEINFO_MAJOR = 1 +MAKEINFO_MINOR = 0 +MAKEINFO_FLAGS = -DMAKEINFO_MAJOR=$(MAKEINFO_MAJOR) -DMAKEINFO_MINOR=$(MAKEINFO_MINOR) + +makeinfo: makeinfo.o getopt.o getopt1.o + $(CC) $(LDFLAGS) -o makeinfo makeinfo.o getopt.o getopt1.o + +makeinfo.o: makeinfo.c + $(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 @@ +@c -*-texinfo-*- +@c This is part of the GNU Emacs Lisp Reference Manual. +@c Copyright (C) 1990, 1991, 1992, 1993, 1994 Free Software Foundation, Inc. +@c See the file elisp.texi for copying conditions. +@setfilename ../info/debugging +@node Debugging, Streams, Byte Compilation, Top +@chapter Debugging Lisp Programs + + There are three ways to investigate a problem in an Emacs Lisp program, +depending on what you are doing with the program when the problem appears. + +@itemize @bullet +@item +If the problem occurs when you run the program, you can use a Lisp +debugger (either the default debugger or Edebug) to investigate what is +happening during execution. + +@item +If the problem is syntactic, so that Lisp cannot even read the program, +you can use the Emacs facilities for editing Lisp to localize it. + +@item +If the problem occurs when trying to compile the program with the byte +compiler, you need to know how to examine the compiler's input buffer. +@end itemize + +@menu +* Debugger:: How the Emacs Lisp debugger is implemented. +* Syntax Errors:: How to find syntax errors. +* Compilation Errors:: How to find errors that show up in byte compilation. +* Edebug:: A source-level Emacs Lisp debugger. +@end menu + + Another useful debugging tool is the dribble file. When a dribble +file is open, Emacs copies all keyboard input characters to that file. +Afterward, you can examine the file to find out what input was used. +@xref{Terminal Input}. + + For debugging problems in terminal descriptions, the +@code{open-termscript} function can be useful. @xref{Terminal Output}. + +@node Debugger +@section The Lisp Debugger +@cindex debugger +@cindex Lisp debugger +@cindex break + + The @dfn{Lisp debugger} provides the ability to suspend evaluation of +a form. While evaluation is suspended (a state that is commonly known +as a @dfn{break}), you may examine the run time stack, examine the +values of local or global variables, or change those values. Since a +break is a recursive edit, all the usual editing facilities of Emacs are +available; you can even run programs that will enter the debugger +recursively. @xref{Recursive Editing}. + +@menu +* Error Debugging:: Entering the debugger when an error happens. +* Infinite Loops:: Stopping and debugging a program that doesn't exit. +* Function Debugging:: Entering it when a certain function is called. +* Explicit Debug:: Entering it at a certain point in the program. +* Using Debugger:: What the debugger does; what you see while in it. +* Debugger Commands:: Commands used while in the debugger. +* Invoking the Debugger:: How to call the function @code{debug}. +* Internals of Debugger:: Subroutines of the debugger, and global variables. +@end menu + +@node Error Debugging +@subsection Entering the Debugger on an Error +@cindex error debugging +@cindex debugging errors + + The most important time to enter the debugger is when a Lisp error +happens. This allows you to investigate the immediate causes of the +error. + + However, entry to the debugger is not a normal consequence of an +error. Many commands frequently get Lisp errors when invoked in +inappropriate contexts (such as @kbd{C-f} at the end of the buffer) and +during ordinary editing it would be very unpleasant to enter the +debugger each time this happens. If you want errors to enter the +debugger, set the variable @code{debug-on-error} to non-@code{nil}. + +@defopt debug-on-error +This variable determines whether the debugger is called when a error is +signaled and not handled. If @code{debug-on-error} is @code{t}, all +errors call the debugger. If it is @code{nil}, none call the debugger. + +The value can also be a list of error conditions that should call the +debugger. For example, if you set it to the list +@code{(void-variable)}, then only errors about a variable that has no +value invoke the debugger. +@end defopt + + To debug an error that happens during loading of the @file{.emacs} +file, use the option @samp{-debug-init}, which binds +@code{debug-on-error} to @code{t} while @file{.emacs} is loaded. + + If your @file{.emacs} file sets @code{debug-on-error}, the effect +lasts only until the end of loading @file{.emacs}. (This is an +undesirable by-product of the @samp{-debug-init} feature.) If you want +@file{.emacs} to set @code{debug-on-error} permanently, use +@code{after-init-hook}, like this: + +@example +(add-hook 'after-init-hook + '(lambda () (setq debug-on-error t))) +@end example + +@node Infinite Loops +@subsection Debugging Infinite Loops +@cindex infinite loops +@cindex loops, infinite +@cindex quitting from infinite loop +@cindex stopping an infinite loop + + When a program loops infinitely and fails to return, your first +problem is to stop the loop. On most operating systems, you can do this +with @kbd{C-g}, which causes quit. + + Ordinary quitting gives no information about why the program was +looping. To get more information, you can set the variable +@code{debug-on-quit} to non-@code{nil}. Quitting with @kbd{C-g} is not +considered an error, and @code{debug-on-error} has no effect on the +handling of @kbd{C-g}. Contrariwise, @code{debug-on-quit} has no effect +on errors.@refill + + Once you have the debugger running in the middle of the infinite loop, +you can proceed from the debugger using the stepping commands. If you +step through the entire loop, you will probably get enough information +to solve the problem. + +@defopt debug-on-quit +This variable determines whether the debugger is called when @code{quit} +is signaled and not handled. If @code{debug-on-quit} is non-@code{nil}, +then the debugger is called whenever you quit (that is, type @kbd{C-g}). +If @code{debug-on-quit} is @code{nil}, then the debugger is not called +when you quit. @xref{Quitting}. +@end defopt + +@node Function Debugging +@subsection Entering the Debugger on a Function Call +@cindex function call debugging +@cindex debugging specific functions + + To investigate a problem that happens in the middle of a program, one +useful technique is to enter the debugger whenever a certain function is +called. You can do this to the function in which the problem occurs, +and then step through the function, or you can do this to a function +called shortly before the problem, step quickly over the call to that +function, and then step through its caller. + +@deffn Command debug-on-entry function-name + This function requests @var{function-name} to invoke the debugger each time +it is called. It works by inserting the form @code{(debug 'debug)} into +the function definition as the first form. + + Any function defined as Lisp code may be set to break on entry, +regardless of whether it is interpreted code or compiled code. If the +function is a command, it will enter the debugger when called from Lisp +and when called interactively (after the reading of the arguments). You +can't debug primitive functions (i.e., those written in C) this way. + + When @code{debug-on-entry} is called interactively, it prompts +for @var{function-name} in the minibuffer. + + If the function is already set up to invoke the debugger on entry, +@code{debug-on-entry} does nothing. + + Caveat: if you redefine a function after using @code{debug-on-entry} +on it, the code to enter the debugger is lost. + + @code{debug-on-entry} returns @var{function-name}. + +@example +@group +(defun fact (n) + (if (zerop n) 1 + (* n (fact (1- n))))) + @result{} fact +@end group +@group +(debug-on-entry 'fact) + @result{} fact +@end group +@group +(fact 3) + @result{} 6 +@end group + +@group +------ Buffer: *Backtrace* ------ +Entering: +* fact(3) + eval-region(4870 4878 t) + byte-code("...") + eval-last-sexp(nil) + (let ...) + eval-insert-last-sexp(nil) +* call-interactively(eval-insert-last-sexp) +------ Buffer: *Backtrace* ------ +@end group + +@group +(symbol-function 'fact) + @result{} (lambda (n) + (debug (quote debug)) + (if (zerop n) 1 (* n (fact (1- n))))) +@end group +@end example +@end deffn + +@deffn Command cancel-debug-on-entry function-name +This function undoes the effect of @code{debug-on-entry} on +@var{function-name}. When called interactively, it prompts for +@var{function-name} in the minibuffer. + +If @code{cancel-debug-on-entry} is called more than once on the same +function, the second call does nothing. @code{cancel-debug-on-entry} +returns @var{function-name}. +@end deffn + +@node Explicit Debug +@subsection Explicit Entry to the Debugger + + You can cause the debugger to be called at a certain point in your +program by writing the expression @code{(debug)} at that point. To do +this, visit the source file, insert the text @samp{(debug)} at the +proper place, and type @kbd{C-M-x}. Be sure to undo this insertion +before you save the file! + + The place where you insert @samp{(debug)} must be a place where an +additional form can be evaluated and its value ignored. (If the value +isn't ignored, it will alter the execution of the program!) The most +common suitable places are inside a @code{progn} or an implicit +@code{progn} (@pxref{Sequencing}). + +@node Using Debugger +@subsection Using the Debugger + + When the debugger is entered, it displays the previously selected +buffer in one window and a buffer named @samp{*Backtrace*} in another +window. The backtrace buffer contains one line for each level of Lisp +function execution currently going on. At the beginning of this buffer +is a message describing the reason that the debugger was invoked (such +as the error message and associated data, if it was invoked due to an +error). + + The backtrace buffer is read-only and uses a special major mode, +Debugger mode, in which letters are defined as debugger commands. The +usual Emacs editing commands are available; thus, you can switch windows +to examine the buffer that was being edited at the time of the error, +switch buffers, visit files, or do any other sort of editing. However, +the debugger is a recursive editing level (@pxref{Recursive Editing}) +and it is wise to go back to the backtrace buffer and exit the debugger +(with the @kbd{q} command) when you are finished with it. Exiting +the debugger gets out of the recursive edit and kills the backtrace +buffer. + +@cindex current stack frame + The contents of the backtrace buffer show you the functions that are +executing and their argument values. It also allows you to specify a +stack frame by moving point to the line describing that frame. (A stack +frame is the place where the Lisp interpreter records information about +a particular invocation of a function.) The frame whose line point is +on is considered the @dfn{current frame}. Some of the debugger commands +operate on the current frame. + + The debugger itself must be run byte-compiled, since it makes +assumptions about how many stack frames are used for the debugger +itself. These assumptions are false if the debugger is running +interpreted. + +@need 3000 + +@node Debugger Commands +@subsection Debugger Commands +@cindex debugger command list + + Inside the debugger (in Debugger mode), these special commands are +available in addition to the usual cursor motion commands. (Keep in +mind that all the usual facilities of Emacs, such as switching windows +or buffers, are still available.) + + The most important use of debugger commands is for stepping through +code, so that you can see how control flows. The debugger can step +through the control structures of an interpreted function, but cannot do +so in a byte-compiled function. If you would like to step through a +byte-compiled function, replace it with an interpreted definition of the +same function. (To do this, visit the source file for the function and +type @kbd{C-M-x} on its definition.) + + Here is a list of Debugger mode commands: + +@table @kbd +@item c +Exit the debugger and continue execution. When continuing is possible, +it resumes execution of the program as if the debugger had never been +entered (aside from the effect of any variables or data structures you +may have changed while inside the debugger). + +Continuing is possible after entry to the debugger due to function entry +or exit, explicit invocation, or quitting. You cannot continue if the +debugger was entered because of an error. + +@item d +Continue execution, but enter the debugger the next time any Lisp +function is called. This allows you to step through the +subexpressions of an expression, seeing what values the subexpressions +compute, and what else they do. + +The stack frame made for the function call which enters the debugger in +this way will be flagged automatically so that the debugger will be +called again when the frame is exited. You can use the @kbd{u} command +to cancel this flag. + +@item b +Flag the current frame so that the debugger will be entered when the +frame is exited. Frames flagged in this way are marked with stars +in the backtrace buffer. + +@item u +Don't enter the debugger when the current frame is exited. This +cancels a @kbd{b} command on that frame. + +@item e +Read a Lisp expression in the minibuffer, evaluate it, and print the +value in the echo area. The debugger alters certain important variables +as part of its operation; @kbd{e} temporarily restores their +outside-the-debugger values so you can examine them. This makes the +debugger more transparent. By contrast, @kbd{M-@key{ESC}} does nothing +special in the debugger; it shows you the variable values within the +debugger. + +@item q +Terminate the program being debugged; return to top-level Emacs +command execution. + +If the debugger was entered due to a @kbd{C-g} but you really want +to quit, and not debug, use the @kbd{q} command. + +@item r +Return a value from the debugger. The value is computed by reading an +expression with the minibuffer and evaluating it. + +The @kbd{r} command makes a difference when the debugger was invoked due +to exit from a Lisp call frame (as requested with @kbd{b}); then the +value specified in the @kbd{r} command is used as the value of that +frame. + +You can't use @kbd{r} when the debugger was entered due to an error. +@end table + +@node Invoking the Debugger +@subsection Invoking the Debugger + + Here we describe fully the function used to invoke the debugger. + +@defun debug &rest debugger-args +This function enters the debugger. It switches buffers to a buffer +named @samp{*Backtrace*} (or @samp{*Backtrace*<2>} if it is the second +recursive entry to the debugger, etc.), and fills it with information +about the stack of Lisp function calls. It then enters a recursive +edit, showing the backtrace buffer in Debugger mode. + +The Debugger mode @kbd{c} and @kbd{r} commands exit the recursive edit; +then @code{debug} switches back to the previous buffer and returns to +whatever called @code{debug}. This is the only way the function +@code{debug} can return to its caller. + +If the first of the @var{debugger-args} passed to @code{debug} is +@code{nil} (or if it is not one of the special values in the table +below), then @code{debeg} displays the rest of its arguments at the the +top of the @samp{*Backtrace*} buffer. This mechanism is used to display +a message to the user. + +However, if the first argument passed to @code{debug} is one of the +following special values, then it has special significance. Normally, +these values are passed to @code{debug} only by the internals of Emacs +and the debugger, and not by programmers calling @code{debug}. + +The special values are: + +@table @code +@item lambda +@cindex @code{lambda} in debug +A first argument of @code{lambda} means @code{debug} was called because +of entry to a function when @code{debug-on-next-call} was +non-@code{nil}. The debugger displays @samp{Entering:} as a line of +text at the top of the buffer. + +@item debug +@code{debug} as first argument indicates a call to @code{debug} because +of entry to a function that was set to debug on entry. The debugger +displays @samp{Entering:}, just as in the @code{lambda} case. It also +marks the stack frame for that function so that it will invoke the +debugger when exited. + +@item t +When the first argument is @code{t}, this indicates a call to +@code{debug} due to evaluation of a list form when +@code{debug-on-next-call} is non-@code{nil}. The debugger displays the +following as the top line in the buffer: + +@smallexample +Beginning evaluation of function call form: +@end smallexample + +@item exit +When the first argument is @code{exit}, it indicates the exit of a +stack frame previously marked to invoke the debugger on exit. The +second argument given to @code{debug} in this case is the value being +returned from the frame. The debugger displays @samp{Return value:} on +the top line of the buffer, followed by the value being returned. + +@item error +@cindex @code{error} in debug +When the first argument is @code{error}, the debugger indicates that +it is being entered because an error or @code{quit} was signaled and not +handled, by displaying @samp{Signaling:} followed by the error signaled +and any arguments to @code{signal}. For example, + +@example +@group +(let ((debug-on-error t)) + (/ 1 0)) +@end group + +@group +------ Buffer: *Backtrace* ------ +Signaling: (arith-error) + /(1 0) +... +------ Buffer: *Backtrace* ------ +@end group +@end example + +If an error was signaled, presumably the variable +@code{debug-on-error} is non-@code{nil}. If @code{quit} was signaled, +then presumably the variable @code{debug-on-quit} is non-@code{nil}. + +@item nil +Use @code{nil} as the first of the @var{debugger-args} when you want +to enter the debugger explicitly. The rest of the @var{debugger-args} +are printed on the top line of the buffer. You can use this feature to +display messages---for example, to remind yourself of the conditions +under which @code{debug} is called. +@end table +@end defun + +@need 5000 + +@node Internals of Debugger +@subsection Internals of the Debugger + + This section describes functions and variables used internally by the +debugger. + +@defvar debugger +The value of this variable is the function to call to invoke the +debugger. Its value must be a function of any number of arguments (or, +more typically, the name of a function). Presumably this function will +enter some kind of debugger. The default value of the variable is +@code{debug}. + +The first argument that Lisp hands to the function indicates why it +was called. The convention for arguments is detailed in the description +of @code{debug}. +@end defvar + +@deffn Command backtrace +@cindex run time stack +@cindex call stack +This function prints a trace of Lisp function calls currently active. +This is the function used by @code{debug} to fill up the +@samp{*Backtrace*} buffer. It is written in C, since it must have access +to the stack to determine which function calls are active. The return +value is always @code{nil}. + +In the following example, a Lisp expression calls @code{backtrace} +explicitly. This prints the backtrace to the stream +@code{standard-output}: in this case, to the buffer +@samp{backtrace-output}. Each line of the backtrace represents one +function call. The line shows the values of the function's arguments if +they are all known. If they are still being computed, the line says so. +The arguments of special forms are elided. + +@smallexample +@group +(with-output-to-temp-buffer "backtrace-output" + (let ((var 1)) + (save-excursion + (setq var (eval '(progn + (1+ var) + (list 'testing (backtrace)))))))) + + @result{} nil +@end group + +@group +----------- Buffer: backtrace-output ------------ + backtrace() + (list ...computing arguments...) + (progn ...) + eval((progn (1+ var) (list (quote testing) (backtrace)))) + (setq ...) + (save-excursion ...) + (let ...) + (with-output-to-temp-buffer ...) + eval-region(1973 2142 #<buffer *scratch*>) + byte-code("... for eval-print-last-sexp ...") + eval-print-last-sexp(nil) +* call-interactively(eval-print-last-sexp) +----------- Buffer: backtrace-output ------------ +@end group +@end smallexample + +The character @samp{*} indicates a frame whose debug-on-exit flag is +set. +@end deffn + +@ignore @c Not worth mentioning +@defopt stack-trace-on-error +@cindex stack trace +This variable controls whether Lisp automatically displays a +backtrace buffer after every error that is not handled. A quit signal +counts as an error for this variable. If it is non-@code{nil} then a +backtrace is shown in a pop-up buffer named @samp{*Backtrace*} on every +error. If it is @code{nil}, then a backtrace is not shown. + +When a backtrace is shown, that buffer is not selected. If either +@code{debug-on-quit} or @code{debug-on-error} is also non-@code{nil}, then +a backtrace is shown in one buffer, and the debugger is popped up in +another buffer with its own backtrace. + +We consider this feature to be obsolete and superseded by the debugger +itself. +@end defopt +@end ignore + +@defvar debug-on-next-call +@cindex @code{eval}, and debugging +@cindex @code{apply}, and debugging +@cindex @code{funcall}, and debugging +If this variable is non-@code{nil}, it says to call the debugger before +the next @code{eval}, @code{apply} or @code{funcall}. Entering the +debugger sets @code{debug-on-next-call} to @code{nil}. + +The @kbd{d} command in the debugger works by setting this variable. +@end defvar + +@defun backtrace-debug level flag +This function sets the debug-on-exit flag of the stack frame @var{level} +levels, giving it the value @var{flag}. If @var{flag} is +non-@code{nil}, this will cause the debugger to be entered when that +frame later exits. Even a nonlocal exit through that frame will enter +the debugger. + +Normally, this function is only called by the debugger. +@end defun + +@defvar command-debug-status +This variable records the debugging status of current interactive +command. Each time a command is called interactively, this variable is +bound to @code{nil}. The debugger can set this variable to leave +information for future debugger invocations during the same command. + +The advantage of using this variable rather that defining another global +variable is that the data will never carry over to a subsequent command +invocation. +@end defvar + +@defun backtrace-frame frame-number +The function @code{backtrace-frame} is intended for use in Lisp +debuggers. It returns information about what computation is happening +in the stack frame @var{frame-number} levels down. + +If that frame has not evaluated the arguments yet (or is a special +form), the value is @code{(nil @var{function} @var{arg-forms}@dots{})}. + +If that frame has evaluated its arguments and called its function +already, the value is @code{(t @var{function} +@var{arg-values}@dots{})}. + +In the return value, @var{function} is whatever was supplied as @sc{car} +of evaluated list, or a @code{lambda} expression in the case of a macro +call. If the function has a @code{&rest} argument, that is represented +as the tail of the list @var{arg-values}. + +If the argument is out of range, @code{backtrace-frame} returns +@code{nil}. +@end defun + +@node Syntax Errors +@section Debugging Invalid Lisp Syntax + + The Lisp reader reports invalid syntax, but cannot say where the real +problem is. For example, the error ``End of file during parsing'' in +evaluating an expression indicates an excess of open parentheses (or +square brackets). The reader detects this imbalance at the end of the +file, but it cannot figure out where the close parenthesis should have +been. Likewise, ``Invalid read syntax: ")"'' indicates an excess close +parenthesis or missing open parenthesis, but does not say where the +missing parenthesis belongs. How, then, to find what to change? + + If the problem is not simply an imbalance of parentheses, a useful +technique is to try @kbd{C-M-e} at the beginning of each defun, and see +if it goes to the place where that defun appears to end. If it does +not, there is a problem in that defun. + + However, unmatched parentheses are the most common syntax errors in +Lisp, and we can give further advice for those cases. + +@menu +* Excess Open:: How to find a spurious open paren or missing close. +* Excess Close:: How to find a spurious close paren or missing open. +@end menu + +@node Excess Open +@subsection Excess Open Parentheses + + The first step is to find the defun that is unbalanced. If there is +an excess open parenthesis, the way to do this is to insert a +close parenthesis at the end of the file and type @kbd{C-M-b} +(@code{backward-sexp}). This will move you to the beginning of the +defun that is unbalanced. (Then type @kbd{C-@key{SPC} C-_ C-u +C-@key{SPC}} to set the mark there, undo the insertion of the +close parenthesis, and finally return to the mark.) + + The next step is to determine precisely what is wrong. There is no +way to be sure of this except to study the program, but often the +existing indentation is a clue to where the parentheses should have +been. The easiest way to use this clue is to reindent with @kbd{C-M-q} +and see what moves. + + Before you do this, make sure the defun has enough close parentheses. +Otherwise, @kbd{C-M-q} will get an error, or will reindent all the rest +of the file until the end. So move to the end of the defun and insert a +close parenthesis there. Don't use @kbd{C-M-e} to move there, since +that too will fail to work until the defun is balanced. + + Now you can go to the beginning of the defun and type @kbd{C-M-q}. +Usually all the lines from a certain point to the end of the function +will shift to the right. There is probably a missing close parenthesis, +or a superfluous open parenthesis, near that point. (However, don't +assume this is true; study the code to make sure.) Once you have found +the discrepancy, undo the @kbd{C-M-q}, since the old indentation is +probably appropriate to the intended parentheses. + + After you think you have fixed the problem, use @kbd{C-M-q} again. If +the old indentation actually fit the intended nesting of parentheses, +and you have put back those parentheses, @kbd{C-M-q} should not change +anything. + +@node Excess Close +@subsection Excess Close Parentheses + + To deal with an excess close parenthesis, first insert an +open parenthesis at the beginning of the file and type @kbd{C-M-f} to +find the end of the unbalanced defun. (Then type @kbd{C-@key{SPC} C-_ +C-u C-@key{SPC}} to set the mark there, undo the insertion of the +open parenthesis, and finally return to the mark.) + + Then find the actual matching close parenthesis by typing @kbd{C-M-f} +at the beginning of the defun. This will leave you somewhere short of +the place where the defun ought to end. It is possible that you will +find a spurious close parenthesis in that vicinity. + + If you don't see a problem at that point, the next thing to do is to +type @kbd{C-M-q} at the beginning of the defun. A range of lines will +probably shift left; if so, the missing open parenthesis or spurious +close parenthesis is probably near the first of those lines. (However, +don't assume this is true; study the code to make sure.) Once you have +found the discrepancy, undo the @kbd{C-M-q}, since the old indentation +is probably appropriate to the intended parentheses. + +@node Compilation Errors +@section Debugging Problems in Compilation + + When an error happens during byte compilation, it is normally due to +invalid syntax in the program you are compiling. The compiler prints a +suitable error message in the @samp{*Compile-Log*} buffer, and then +stops. The message may state a function name in which the error was +found, or it may not. Either way, here is how to find out where in the +file the error occurred. + + What you should do is switch to the buffer @w{@samp{ *Compiler Input*}}. +(Note that the buffer name starts with a space, so it does not show +up in @kbd{M-x list-buffers}.) This buffer contains the program being +compiled, and point shows how far the byte compiler was able to read. + + If the error was due to invalid Lisp syntax, point shows exactly where +the invalid syntax was @emph{detected}. The cause of the error is not +necessarily near by! Use the techniques in the previous section to find +the error. + + If the error was detected while compiling a form that had been read +successfully, then point is located at the end of the form. In this +case, it can't localize the error precisely, but can still show you +which function to check. + +@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 @@ +@comment -*-texinfo-*- + +@c This file is intended to be used as a section within the Emacs Lisp +@c Reference Manual. It may also be used by an independent Edebug User +@c Manual, edebug.tex, in which case the Edebug node below should be used +@c with the following links to the Bugs section and to the top level: + +@c , Bugs and Todo List, Top, Top + +@node Edebug, Bugs and Todo List, Top, Top +@section Edebug +@cindex Edebug mode + +@cindex Edebug + Edebug is a source-level debugger for Emacs Lisp programs with which +you can: + +@itemize @bullet +@item +Step through evaluation, stopping before and after each expression. + +@item +Set conditional or unconditional breakpoints. + +@item +Stop when a specified condition is true (the global break event). + +@item +Trace slow or fast, stopping briefly at each stop point, or +at each breakpoint. + +@item +Display expression results and evaluate expressions as if outside of +Edebug. + +@item +Automatically reevaluate a list of expressions and +display their results each time Edebug updates the display. + +@item +Output trace info on function enter and exit. + +@item +Stop when an error occurs. + +@item +Display a backtrace, omitting Edebug's own frames. + +@item +Specify argument evaluation for macros and defining forms. + +@item +Obtain rudimentary coverage testing and frequency counts. +@end itemize + +The first three sections below should tell you enough about Edebug to +enable you to use it. + +@menu +* Using Edebug:: Introduction to use of Edebug. +* Instrumenting:: You must instrument your code + in order to debug it with Edebug. +* Modes: Edebug Execution Modes. Execution modes, stopping more or less often. +* Jumping:: Commands to jump to a specified place. +* Misc: Edebug Misc. Miscellaneous commands. +* Breakpoints:: Setting breakpoints to make the program stop. +* Trapping Errors:: trapping errors with Edebug. +* Views: Edebug Views. Views inside and outside of Edebug. +* Eval: Edebug Eval. Evaluating expressions within Edebug. +* Eval List:: Expressions whose values are displayed + each time you enter Edebug. +* Printing in Edebug:: Customization of printing. +* Trace Buffer:: How to produce trace output in a buffer. +* Coverage Testing:: How to test evaluation coverage. +* The Outside Context:: Data that Edebug saves and restores. +* Instrumenting Macro Calls:: Specifying how to handle macro calls. +* Options: Edebug Options. Option variables for customizing Edebug. +@end menu + +@node Using Edebug +@subsection Using Edebug + + To debug a Lisp program with Edebug, you must first @dfn{instrument} +the Lisp code that you want to debug. A simple way to do this is to +first move point into the definition of a function or macro and then do +@kbd{C-u C-M-x} (@code{eval-defun} with a prefix argument). See +@ref{Instrumenting}, for alternative ways to instrument code. + + Once a function is instrumented, any call to the function activates +Edebug. Activating Edebug may stop execution and let you step through +the function, or it may update the display and continue execution while +checking for debugging commands, depending on which Edebug execution +mode you have selected. The default execution mode is step, which does +stop execution. @xref{Edebug Execution Modes}. + + Within Edebug, you normally view an Emacs buffer showing the source of +the Lisp code you are debugging. This is referred to as the @dfn{source +code buffer}. This buffer is temporarily read-only. + + An arrow at the left margin indicates the line where the function is +executing. Point initially shows where within the line the function is +executing, but this ceases to be true if you move point yourself. + + If you instrument the definition of @code{fac} (shown below) and then +execute @code{(fac 3)}, here is what you normally see. Point is at the +open-parenthesis before @code{if}. + +@example +(defun fac (n) +=>@point{}(if (< 0 n) + (* n (fac (1- n))) + 1)) +@end example + +@cindex stop points +The places within a function where Edebug can stop execution are called +@dfn{stop points}. These occur both before and after each subexpression +that is a list, and also after each variable reference. +Here we show with periods the stop points found in the function +@code{fac}: + +@example +(defun fac (n) + .(if .(< 0 n.). + .(* n. .(fac (1- n.).).). + 1).) +@end example + +The special commands of Edebug are available in the source code buffer +in addition to the commands of Emacs Lisp mode. For example, you can +type the Edebug command @key{SPC} to execute until the next stop point. +If you type @key{SPC} once after entry to @code{fac}, here is the +display you will see: + +@example +(defun fac (n) +=>(if @point{}(< 0 n) + (* n (fac (1- n))) + 1)) +@end example + +When Edebug stops execution after an expression, it displays the +expression's value in the echo area. + +Other frequently used commands are @kbd{b} to set a breakpoint at a stop +point, @kbd{g} to execute until a breakpoint is reached, and @kbd{q} to +exit Edebug and return to the top-level command loop. Type @kbd{?} to +display a list of all Edebug commands. + +@node Instrumenting +@subsection Instrumenting for Edebug + + In order to use Edebug to debug Lisp code, you must first +@dfn{instrument} the code. Instrumenting code inserts additional code +into it, code which invokes Edebug at the proper places. + + Once a function is instrumented, any call to the function activates +Edebug. This may or may not stop execution, depending on the Edebug +execution mode in use. Some Edebug modes only update the display to +indicate the progress of the evaluation without stopping execution. + +@kindex C-M-x +@findex eval-defun (Edebug) + Once you have loaded Edebug, the command @kbd{C-M-x} +(@code{eval-defun}) is redefined so that when invoked with a prefix +argument on a definition, it instruments the definition before +evaluating it. (The source code itself is not modified.) If the +variable @code{edebug-all-defs} is non-@code{nil}, that inverts the +meaning of the prefix argument: then @kbd{C-M-x} instruments the +definition @emph{unless} it has a prefix argument. The default value of +@code{edebug-all-defs} is @code{nil}. The command @kbd{M-x +edebug-all-defs} toggles the value of the variable +@code{edebug-all-defs}. + +@findex edebug-all-forms +@findex eval-region (Edebug) +@findex eval-current-buffer (Edebug) + If @code{edebug-all-defs} is non-@code{nil}, then the commands +@code{eval-region}, @code{eval-current-buffer}, and @code{eval-buffer} +also instrument any definitions they evaluate. Similarly, +@code{edebug-all-forms} controls whether @code{eval-region} should +instrument @emph{any} form, even non-defining forms. This doesn't apply +to loading or evaluations in the minibuffer. The command @kbd{M-x +edebug-all-forms} toggles this option. + +@findex edebug-eval-top-level-form +Another command, @kbd{M-x edebug-eval-top-level-form}, is available to +instrument any top-level form regardless of the value of +@code{edebug-all-defs} or @code{edebug-all-forms}. + +When Edebug is about to instrument code for the first time in a session, +it runs the hook @code{edebug-setup-hook}, then sets it to @code{nil}. +You can use this to load up Edebug specifications associated with a +package you are using, but only when you also use Edebug. + +While Edebug is active, the command @kbd{I} +(@code{edebug-instrument-callee}) instruments the definition of the +function or macro called by the list form after point, if is not already +instrumented. This is possible only if Edebug knows where to find the +source for that function; after loading Edebug, @code{eval-region} +records the position of every definition it evaluates, even if not +instrumenting it. See also the @kbd{i} command (@pxref{Jumping}), which +steps into the call after instrumenting the function. + +@cindex special forms (Edebug) +@cindex interactive commands (Edebug) +@cindex anonymous lambda expressions (Edebug) +@cindex Common Lisp (Edebug) +@pindex cl.el (Edebug) +@pindex cl-specs.el + Edebug knows how to instrument all the standard special forms, an +interactive form with an expression argument, anonymous lambda +expressions, and other defining forms. Edebug cannot know what a +user-defined macro will do with the arguments of a macro call, so you +must tell it; @xref{Instrumenting Macro Calls}, for details. + +@findex eval-expression (Edebug) + To remove instrumentation from a definition, simply reevaluate its +definition in a way that does not instrument. There are two ways of +evaluating forms without instrumenting them: from a file with +@code{load}, and from the minibuffer with @code{eval-expression} +(@kbd{M-ESC}). + + If Edebug detects a syntax error while instrumenting, it leaves point +at the erroneous code and signals an @code{invalid-read-syntax} error. + + @xref{Edebug Eval}, for other evaluation functions available +inside of Edebug. + +@node Edebug Execution Modes +@subsection Edebug Execution Modes + +@cindex Edebug execution modes +Edebug supports several execution modes for running the program you are +debugging. We call these alternatives @dfn{Edebug execution modes}; do +not confuse them with major or minor modes. The current Edebug mode +determines how far Edebug continues execution before stopping---whether +it stops at each stop point, or continues to the next breakpoint, for +example---and how much Edebug displays the progress of the evaluation +before it stops. + +Normally, you specify the Edebug execution mode by typing a command to +continue the program in a certain mode. Here is a table of these +commands. All except for @kbd{S} resume execution of the program, at +least for a certain distance. + +@table @kbd +@item S +Stop: don't execute any more of the program for now, just wait for more +Edebug commands (@code{edebug-stop}). + +@item @key{SPC} +Step: stop at the next stop point encountered (@code{edebug-step-mode}). + +@item n +Next: stop at the next stop point encountered after an expression +(@code{edebug-next-mode}). Also see @code{edebug-forward-sexp} in +@ref{Edebug Misc}. + +@item t +Trace: pause one second at each Edebug stop point (@code{edebug-trace-mode}). + +@item T +Rapid trace: update the display at each stop point, but don't actually +pause (@code{edebug-Trace-fast-mode}). + +@item g +Go: run until the next breakpoint (@code{edebug-go-mode}). @xref{Breakpoints}. + +@item c +Continue: pause one second at each breakpoint, and then continue +(@code{edebug-continue-mode}). + +@item C +Rapid continue: move point to each breakpoint, but don't pause +(@code{edebug-Continue-fast-mode}). + +@item G +Go non-stop: ignore breakpoints (@code{edebug-Go-nonstop-mode}). You +can still stop the program by typing @kbd{S}, or any editing command. +@end table + +In general, the execution modes earlier in the above list run the +program more slowly or stop sooner. + +While executing or tracing, you can interrupt the execution by typing +any Edebug command. Edebug stops the program at the next stop point and +then executes the command that you typed. For example, typing @kbd{t} +during execution switches to trace mode at the next stop point. You can +use @kbd{S} to stop execution without doing anything else. + +If your function happens to read input, a character you type intending +to interrupt execution may be read by the function instead. You can +avoid such unintended results by paying attention to when your program +wants input. + +@cindex keyboard macros (Edebug) +Keyboard macros containing the commands in this section do not +completely work: exiting from Edebug, to resume the program, loses track +of the keyboard macro. This is not easy to fix. Also, defining or +executing a keyboard macro outside of Edebug does not affect commands +inside Edebug. This is usually an advantage. But see the +@code{edebug-continue-kbd-macro} option (@pxref{Edebug Options}). + +When you enter a new Edebug level, the initial execution mode comes from +the value of the variable @code{edebug-initial-mode}. By default, this +specifies step mode. Note that you may reenter the same Edebug level +several times if, for example, an instrumented function is called +several times from one command. + + +@node Jumping +@subsection Jumping + + The commands described in this section execute until they reach a +specified location. All except @kbd{i} make a temporary breakpoint to +establish the place to stop, then switch to go mode. Any other +breakpoint reached before the intended stop point will also stop +execution. @xref{Breakpoints}, for the details on breakpoints. + + These commands may fail to work as expected in case of nonlocal exit, +because a nonlocal exit can bypass the temporary breakpoint where you +expected the program to stop. + +@table @kbd +@item h +Proceed to the stop point near where point is (@code{edebug-goto-here}). + +@item f +Run the program forward over one expression +(@code{edebug-forward-sexp}). + +@item o +Run the program until the end of the containing sexp. + +@item i +Step into the function or macro called by the form after point. +@end table + +The @kbd{h} command proceeds to the stop point near the current location +if point, using a temporary breakpoint. See @ref{Breakpoints}, for more +about breakpoints. + +The @kbd{f} command runs the program forward over one expression. More +precisely, it sets a temporary breakpoint at the position that +@kbd{C-M-f} would reach, then executes in go mode so that the program +will stop at breakpoints. + +With a prefix argument @var{n}, the temporary breakpoint is placed +@var{n} sexps beyond point. If the containing list ends before @var{n} +more elements, then the place to stop is after the containing +expression. + +Be careful that the position @kbd{C-M-f} finds is a place that the +program will really get to; this may not be true in a +@code{cond}, for example. + +The @kbd{f} command does @code{forward-sexp} starting at point, rather +than at the stop point, for flexibility. If you want to execute one +expression @emph{from the current stop point}, type @kbd{w} first, to +move point there, and then type @kbd{f}. + +The @kbd{o} command continues ``out of'' an expression. It places a +temporary breakpoint at the end of the sexp containing point. If the +containing sexp is a function definition itself, it continues until just +before the last sexp in the definition. If that is where you are now, +it returns from the function and then stops. In other words, this +command does not exit the currently executing function unless you are +positioned after the last sexp. + +The @kbd{i} command steps into the function or macro called by the list +form after point. Note that the form need not be the one about to be +evaluated. But if the form is a function call about to be evaluated, +remember to use this command before any of the arguments are evaluated, +since otherwise it will be too late. + +The @kbd{i} command instruments the function or macro it's supposed to +step into, if it isn't instrumented already. This is convenient, but keep +in mind that the function or macro remains instrumented unless you explicitly +arrange to deinstrument it. + +@node Edebug Misc +@subsection Miscellaneous Edebug Commands + + Some miscellaneous Edebug commands are described here. + +@table @kbd +@item ? +Display the help message for Edebug (@code{edebug-help}). + +@item C-] +Abort one level back to the previous command level +(@code{abort-recursive-edit}). + +@item q +Return to the top level editor command loop (@code{top-level}). This +exits all recursive editing levels, including all levels of Edebug +activity. However, instrumented code protected with +@code{unwind-protect} or @code{condition-case} forms may resume +debugging. + +@item Q +Like @kbd{q} but don't stop even for protected code +(@code{top-level-nonstop}). + +@item r +Redisplay the most recently known expression result in the echo area +(@code{edebug-previous-result}). + +@item d +Display a backtrace, excluding Edebug's own functions for clarity +(@code{edebug-backtrace}). + +You cannot use debugger commands in the backtrace buffer in Edebug as +you would in the standard debugger. + +The backtrace buffer is killed automatically when you continue +execution. +@end table + +>From the Edebug recursive edit, you may invoke commands that activate +Edebug again recursively. Any time Edebug is active, you can quit to +the top level with @kbd{q} or abort one recursive edit level with +@kbd{C-]}. You can display a backtrace of all the +pending evaluations with @kbd{d}. + +@node Breakpoints +@subsection Breakpoints + +@cindex breakpoints +Edebug's step mode stops execution at the next stop point reached. +There are three other ways to stop Edebug execution once it has started: +breakpoints, the global break condition, and source breakpoints. + +While using Edebug, you can specify @dfn{breakpoints} in the program you +are testing: points where execution should stop. You can set a +breakpoint at any stop point, as defined in @ref{Using Edebug}. For +setting and unsetting breakpoints, the stop point that is affected is +the first one at or after point in the source code buffer. Here are the +Edebug commands for breakpoints: + +@table @kbd +@item b +Set a breakpoint at the stop point at or after point +(@code{edebug-set-breakpoint}). If you use a prefix argument, the +breakpoint is temporary (it turns off the first time it stops the +program). + +@item u +Unset the breakpoint (if any) at the stop point at or after +point (@code{edebug-unset-breakpoint}). + +@item x @var{condition} @key{RET} +Set a conditional breakpoint which stops the program only if +@var{condition} evaluates to a non-@code{nil} value +(@code{edebug-set-conditional-breakpoint}). With a prefix argument, the +breakpoint is temporary. + +@item B +Move point to the next breakpoint in the definition +(@code{edebug-next-breakpoint}). +@end table + +While in Edebug, you can set a breakpoint with @kbd{b} and unset one +with @kbd{u}. First move point to the Edebug stop point of your choice, +then type @kbd{b} or @kbd{u} to set or unset a breakpoint there. +Unsetting a breakpoint where none has been set has no effect. + +Reevaluating or reinstrumenting a definition forgets all its breakpoints. + +A @dfn{conditional breakpoint} tests a condition each time the program +gets there. Any errors that occur as a result of evaluating the +condition are ignored, as if the result were @code{nil}. To set a +conditional breakpoint, use @kbd{x}, and specify the condition +expression in the minibuffer. Setting a conditional breakpoint at a +stop point that has a previously established conditional breakpoint puts +the previous condition expression in the minibuffer so you can edit it. + +You can make a conditional or unconditional breakpoint +@dfn{temporary} by using a prefix arg with the command to set the +breakpoint. When a temporary breakpoint stops the program, it is +automatically unset. + +Edebug always stops or pauses at a breakpoint except when the Edebug +mode is Go-nonstop. In that mode, it ignores breakpoints entirely. + +To find out where your breakpoints are, use the @kbd{B} command, which +moves point to the next breakpoint in the definition following point, or +to the first breakpoint if there are no following breakpoints. This +command does not continue execution---it just moves point in the buffer. + +@menu +* Global Break Condition:: Breaking on an event. +* Source Breakpoints:: Embedding breakpoints in source code. +@end menu + + +@node Global Break Condition +@subsubsection Global Break Condition + +@cindex stopping on events +@cindex global break condition + A @dfn{global break condition} stops execution when a specified +condition is satisfied, no matter where that may occur. Edebug +evaluates the global break condition at every stop point. If it +evaluates to a non-@code{nil} value, then execution stops or pauses +depending on the execution mode, as if a breakpoint had been hit. If +evaluating the condition gets an error, execution does not stop. + +@findex edebug-set-global-break-condition +@vindex edebug-global-break-condition + You can set or edit the condition expression, stored in +@code{edebug-global-break-condition}, using the @kbd{X} command +(@code{edebug-set-global-break-condition}). + + The global break condition is the simplest way to find where in your +code some event occurs, but it makes code run much more slowly. So you +should reset the condition to @code{nil} when not using it. + +@node Source Breakpoints +@subsubsection Source Breakpoints + +@findex edebug +@cindex source breakpoints + All breakpoints in a definition are forgotten each time you +reinstrument it. To make a breakpoint that won't be forgotten, you can +write a @dfn{source breakpoint}, which is simply a call to the function +@code{edebug} in your source code. You can, of course, make such a call +conditional. For example, in the @code{fac} function, insert the first +line as shown below to stop when the argument reaches zero: + +@example +(defun fac (n) + (if (= n 0) (edebug)) + (if (< 0 n) + (* n (fac (1- n))) + 1)) +@end example + +When the @code{fac} definition is instrumented and the function is +called, the call to @code{edebug} acts as a breakpoint. Depending on +the execution mode, Edebug stops or pauses there. + +If no instrumented code is being executed when @code{edebug} is called, +that function calls @code{debug}. +@c This may not be a good idea anymore. + +@node Trapping Errors +@subsection Trapping Errors + +Emacs normally displays an error message when an error is signaled and +not handled with @code{condition-case}. While Edebug is active, it +normally responds to all unhandled errors. You can customize this with +the options @code{edebug-on-error} and @code{edebug-on-quit}; see +@ref{Edebug Options}. + +When Edebug responds to an error, it shows the last stop point +encountered before the error. This may be the location of a call to a +function which was not instrumented, within which the error actually +occurred. For an unbound variable error, the last known stop point +might be quite distant from the offending variable reference. In that +case you might want to display a full backtrace (@pxref{Edebug Misc}). + +If you change @code{debug-on-error} or @code{debug-on-quit} while +Edebug is active, these changes will be forgotten when Edebug becomes +inactive. Furthermore, during Edebug's recursive edit, these variables +are bound to the values they had outside of Edebug. + +@ignore @c I don't want to document something that works only partly -- rms. +Edebug can also trap signals even if they are handled. If +@code{debug-on-error} is a list of signal names, Edebug will stop when +any of these errors are signaled. Edebug shows you the last known stop +point just as for unhandled errors. After you continue execution, the +error is signaled again (but without being caught by Edebug). Edebug +can only trap errors that are handled if they are signaled in Lisp code +(not subroutines) since it does so by temporarily replacing the +@code{signal} function. +@end ignore + +@node Edebug Views +@subsection Edebug Views + +These Edebug commands let you view aspects of the buffer and window +status that obtained before entry to Edebug. + +@table @kbd +@item v +View the outside window configuration (@code{edebug-view-outside}). + +@item p +Temporarily display the outside current buffer with point at its outside +position (@code{edebug-bounce-point}). With a prefix argument @var{n}, +pause for @var{n} seconds instead. + +@item w +Move point back to the current stop point (@code{edebug-where}) in the +source code buffer. Also, if you use this command in a different window +displaying the same buffer, that window will be used instead to display +the current definition in the future. + +@item W +Forget the saved outside window configuration---so that the current +window configuration will remain unchanged when you next exit Edebug (by +continuing the program). Also toggle the @code{edebug-save-windows} +variable. +@ignore @c This text is implementation-oriented and doesn't emphasize + what users really want to know. +Toggle the @code{edebug-save-windows} variable which indicates whether +the outside window configuration is saved and restored +(@code{edebug-toggle-save-windows}). Also, each time it is toggled on, +make the outside window configuration the same as the current window +configuration. +@end ignore +@end table + +You can view the outside window configuration with @kbd{v} or just +bounce to the point in the current buffer with @kbd{p}, even if +it is not normally displayed. After moving point, you may wish to jump +back to the stop point with @kbd{w} from a source code buffer. + +@ignore I don't understand this -- rms +If you type @kbd{W} twice, Edebug continues saving and restoring an +outside window configuration, but updates it to match the current +configuration. You can use this to add another buffer to be displayed +whenever Edebug is active. However, the automatic redisplay of +@samp{*edebug*} and @samp{*edebug-trace*} may conflict with the buffers +you wish to see unless you have enough windows open. + +With a prefix argument, @code{W} only toggles saving and restoring of +the selected window. To specify a window that is not displaying the +source code buffer, you must use @kbd{C-x X W} from the global keymap. +@end ignore + +@node Edebug Eval +@subsection Evaluation + +While within Edebug, you can evaluate expressions ``as if'' Edebug were +not running. Edebug tries to be invisible to the expression's +evaluation and printing. Evaluation of expressions that cause side +effects will work as expected except for things that Edebug explicitly +saves and restores. @xref{The Outside Context}, for details on this +process. + +@table @kbd +@item e @var{exp} @key{RET} +Evaluate expression @var{exp} in the context outside of Edebug +(@code{edebug-eval-expression}). That is, Edebug tries to minimize its +interference with the evaluation. + +@item M-@key{ESC} @var{exp} @key{RET} +Evaluate expression @var{exp} in the context of Edebug itself. + +@item C-x C-e +Evaluate the expression before point, in the context outside of Edebug +(@code{edebug-eval-last-sexp}). +@end table + +@cindex lexical binding (Edebug) +Edebug supports evaluation of expressions containing references to +lexically bound symbols created by the following constructs in +@file{cl.el} (version 2.03 or later): @code{lexical-let}, +@code{macrolet}, and @code{symbol-macrolet}. + + +@node Eval List +@subsection Evaluation List Buffer + +You can use the @dfn{evaluation list buffer}, called @samp{*edebug*}, to +evaluate expressions interactively. You can also set up the +@dfn{evaluation list} of expressions to be evaluated automatically each +time Edebug updates the display. + +@table @kbd +@item E +Switch to the evaluation list buffer @samp{*edebug*} +(@code{edebug-visit-eval-list}). +@end table + +In the @samp{*edebug*} buffer you can use the commands of Lisp +Interaction mode (@pxref{Lisp Interaction,,, emacs, The GNU Emacs +Manual}) as well as these special commands: + +@table @kbd +@item LFD +Evaluate the expression before point, in the outside context, and insert +the value in the buffer (@code{edebug-eval-print-last-sexp}). + +@item C-x C-e +Evaluate the expression before point, in the context outside of Edebug +(@code{edebug-eval-last-sexp}). + +@item C-c C-u +Build a new evaluation list from contents of the buffer +(@code{edebug-update-eval-list}). + +@item C-c C-d +Delete the evaluation list group that point is in +(@code{edebug-delete-eval-item}). + +@item C-c C-w +Switch back to the source code buffer at the current stop point +(@code{edebug-where}). +@end table + +You can evaluate expressions in the evaluation list window with +@kbd{LFD} or @kbd{C-x C-e}, just as you would in @samp{*scratch*}; +but they are evaluated in the context outside of Edebug. + +The expressions you enter interactively (and their results) are lost +when you continue execution; but you can set up an @dfn{evaluation list} +consisting of expressions to be evaluated each time execution stops. + +@cindex evaluation list group +To do this, write one or more @dfn{evaluation list groups} in the +evaluation list buffer. An evaluation list group consists of one or +more Lisp expressions. Groups are separated by comment lines. + +The command @kbd{C-c C-u} (@code{edebug-update-eval-list}) rebuilds the +evaluation list, scanning the buffer and using the first expression of +each group. + +Be careful not to add expressions that execute instrumented code since +that would cause an infinite loop. +@c There ought to be a way to fix this. + +Redisplaying the evaluation list works by inserting each expression in +the buffer, followed by its current value. It also inserts comment +lines so that each expression becomes its own group. Thus, if you type +@kbd{C-c C-u} again without changing the buffer text, the evaluation +list is effectively unchanged. + +If an error occurs during an evaluation from the evaluation list, the +error message is displayed in a string as if it were the result. +Therefore, expressions that use variables not currently valid do not +interrupt your debugging. + +Here is an example of what the evaluation list window looks like after +several expressions have been added to it: + +@smallexample +(current-buffer) +#<buffer *scratch*> +;--------------------------------------------------------------- +(selected-window) +#<window 16 on *scratch*> +;--------------------------------------------------------------- +(point) +196 +;--------------------------------------------------------------- +bad-var +"Symbol's value as variable is void: bad-var" +;--------------------------------------------------------------- +(recursion-depth) +0 +;--------------------------------------------------------------- +this-command +eval-last-sexp +;--------------------------------------------------------------- +@end smallexample + +To delete a group, move point into it and type @kbd{C-c C-d}, or simply +delete the text for the group and update the evaluation list with +@kbd{C-c C-u}. To add a new expression to the evaluation list, insert +the expression at a suitable place, and insert a new comment line. (You +need not insert dashes in the comment line---its contents don't matter.) +Then type @kbd{C-c C-u}. + +After selecting @samp{*edebug*}, you can return to the source code +buffer with @kbd{C-c C-w}. The @samp{*edebug*} buffer is killed when +you continue execution, and recreated next time it is needed. + + +@node Printing in Edebug +@subsection Printing in Edebug + +@cindex printing (Edebug) +@cindex printing circular structures +@pindex cust-print + If an expression in your program produces a value containing circular +list structure, you may get an error when Edebug attempts to print it. + +@vindex edebug-print-length +@vindex edebug-print-level + One way to cope with circular structure is to set @code{print-length} +or @code{print-level} to truncate the printing. Edebug does this for +you; it binds @code{print-length} and @code{print-level} to 50 if they +were @code{nil}. (Actually, the variables @code{edebug-print-length} +and @code{edebug-print-level} specify the values to use within Edebug.) +@xref{Output Variables}. + + You can also print circular structures and structures that share +elements more informatively by using the @file{cust-print} package. + + To load @file{cust-print} and activate custom printing only for +Edebug, simply use the command @kbd{M-x edebug-install-custom-print}. +To restore the standard print functions, use @kbd{M-x +edebug-uninstall-custom-print}. + + Here is an example of code that creates a circular structure: + +@example +(setq a '(x y)) +(setcar a a)) +@end example + +@noindent +Custom printing prints this as @samp{Result: #1=(#1# y)}. The +@samp{#1=} notation labels the structure that follows it with the label +@samp{1}, and the @samp{#1#} notation references the previously labelled +structure. This notation is used for any shared elements of lists or +vectors. + + Other programs can also use custom printing; see @file{cust-print.el} +for details. + +@node Trace Buffer +@subsection Trace Buffer +@cindex trace buffer + + Edebug can record an execution trace in a buffer named +@samp{*edebug-trace*}. This is a log of function calls and returns, +showing the function names and their arguments and values. To enable +trace recording, set @code{edebug-trace} to a non-@code{nil} value. + + Making a trace buffer is not the same thing as using trace execution +mode (@pxref{Edebug Execution Modes}). + + When trace recording is enabled, each function entry and exit adds +lines to the trace buffer. A function entry record looks like +@samp{::::@{} followed by the function name and argument values. A +function exit record looks like @samp{::::@}} followed by the function +name and result of the function. + + The number of @samp{:}s in an entry shows its recursion depth. You +can use the braces in the trace buffer to find the matching beginning or +end of function calls. + +@findex edebug-print-trace-before +@findex edebug-print-trace-after + You can customize trace recording for function entry and exit by +redefining the functions @code{edebug-print-trace-before} and +@code{edebug-print-trace-after}. + +@defmac edebug-tracing string body@dots{} +This macro requests additional trace information around the execution +of the @var{body} forms. The argument @var{string} specifies text +to put in the trace buffer. All the arguments are evaluated. +@code{edebug-tracing} returns the value of the last form in @var{body}. +@end defmac + +@defun edebug-trace format-string &rest format-args +This function inserts text in the trace buffer. It computes the text +with @code{(apply 'format @var{format-string} @var{format-args})}. +It also inserts a newline to separate entries. +@end defun + + @code{edebug-tracing} and @code{edebug-trace} insert lines in the trace +buffer even if Edebug is not active. + + Adding text to the trace buffer also scrolls its window to show the +last lines inserted. + +@ignore @c too vague +There may be some display problems if you use +tracing along with the evaluation list. +@end ignore + +@node Coverage Testing +@subsection Coverage Testing + +@cindex coverage testing +@cindex frequency counts +@cindex performance analysis +Edebug provides rudimentary coverage testing and display of execution +frequency. All execution of an instrumented function accumulates +frequency counts, both before and after evaluation of each instrumented +expression, even if the execution mode is Go-nonstop. Coverage testing +is more expensive, so it is only done if @code{edebug-test-coverage} is +non-@code{nil}. The command @kbd{M-x edebug-display-freq-count} +displays both the frequency data and the coverage data (if recorded). + +@deffn Command edebug-display-freq-count +This command displays the frequency count data for each line of the +current definition. + +The frequency counts appear comment lines after each line of code, and +you can undo all insertions with one @code{undo} command. The counts +are appear under the @kbd{(} before an expression or the @kbd{)} after +an expression, or on the last character of a symbol. Values do not appear if +they are equal to the previous count on the same line. + +The character @samp{=} following the count for an expression says that +the expression has returned the same value each time it was evaluated +This is the only coverage information that Edebug records. + +To clear the frequency count and coverage data for a definition, +reinstrument it. +@end deffn + +For example, after evaluating @code{(fac 5)} with a source +breakpoint, and setting @code{edebug-test-coverage} to @code{t}, when +the breakpoint is reached, the frequency data looks like this: + +@example +(defun fac (n) + (if (= n 0) (edebug)) +;#6 1 0 =5 + (if (< 0 n) +;#5 = + (* n (fac (1- n))) +;# 5 0 + 1)) +;# 0 +@end example + +The comment lines show that @code{fac} has been called 6 times. The +first @code{if} statement has returned 5 times with the same result each +time; the same is true of the condition on the second @code{if}. +The recursive call of @code{fac} has not returned at all. + + +@node The Outside Context +@subsection The Outside Context + +Edebug tries to be transparent to the program you are debugging, but it +does not succeed completely. Edebug also tries to be transparent when +you evaluate expressions with @kbd{e} or with the evaluation list +buffer, by temporarily restoring the outside context. This section +explains precisely what context Edebug restores, and how Edebug fails to +be completely transparent. + +@c This can be fixed and should be +The same mechanism that avoids masking certain variable's outside values +also currently makes it impossible to set these variables within Edebug. + +@menu +* Checking Whether to Stop:: When Edebug decides what to do. +* Edebug Display Update:: When Edebug updates the display. +* Edebug Recursive Edit:: When Edebug stops execution. +@end menu + +@node Checking Whether to Stop +@subsubsection Checking Whether to Stop + +Whenever Edebug is entered just to think about whether to take some +action, it needs to save and restore certain data. + +@itemize @bullet +@item +@code{max-lisp-eval-depth} and @code{max-specpdl-size} are both +incremented one time to reduce Edebug's impact on the stack. +You could, however, still run out of stack space when using Edebug. + +@item +The state of keyboard macro execution is saved and restored. While +Edebug is active, @code{executing-macro} is bound to +@code{edebug-continue-kbd-macro}. + +@end itemize + + +@node Edebug Display Update +@subsubsection Edebug Display Update + +When Edebug needs to display something (e.g., in trace mode), it saves +the current window configuration from ``outside'' Edebug (@pxref{Window +Configurations,,, elisp, GNU Emacs Lisp Reference Manual}). When +you exit Edebug (by continuing the program), it restores the previous +window configuration. + +Emacs redisplays only when it pauses. Usually, when you continue +execution, the program comes back into Edebug at a breakpoint or after +stepping without pausing or reading input in between. In such cases, +Emacs never gets a chance to redisplay the ``outside'' configuration. +What you see is the same window configuration as the last time Edebug +was active, with no interruption. + +Entry to Edebug for displaying something also saves and restores the +following data, but some of these are deliberately not restored if an +error or quit signal occurs. + +@itemize @bullet +@item +@cindex current buffer point and mark (Edebug) +Which buffer is current, and the positions of point and the mark in the +current buffer, are saved and restored. + +@item +@cindex window configuration (Edebug) +The outside window configuration is saved and restored if +@code{edebug-save-windows} is non-@code{nil} (@pxref{Edebug Display Update}). + +The window configuration is not restored on error or quit, but the +outside selected window @emph{is} reselected even on error or quit in +case a @code{save-excursion} is active. If the value of +@code{edebug-save-windows} is a list, only the listed windows are saved +and restored. + +The window start and horizontal scrolling of the source code buffer are +not restored, however, so that the display remains coherent within Edebug. + +@item +@vindex edebug-save-displayed-buffer-points +The value of point in each displayed buffer is saved and restored if +@code{edebug-save-displayed-buffer-points} is non-@code{nil}. + +@item +The variables @code{overlay-arrow-position} and +@code{overlay-arrow-string} are saved and restored. So you can safely +invoke Edebug from the recursive edit elsewhere in the same buffer. + +@item +@code{cursor-in-echo-area} is locally bound to @code{nil} so that +the cursor shows up in the window. +@end itemize + +@node Edebug Recursive Edit +@subsubsection Edebug Recursive Edit + +When Edebug is entered and actually reads commands from the user, it +saves (and later restores) these additional data: + +@itemize @bullet +@item +The current match data. @xref{Match Data}. + +@item +@code{last-command}, @code{this-command}, @code{last-command-char}, +@code{last-input-char}, @code{last-input-event}, +@code{last-command-event}, @code{last-event-frame}, +@code{last-nonmenu-event}, and @code{track-mouse}. Commands used within +Edebug do not affect these variables outside of Edebug. + +The key sequence returned by @code{this-command-keys} is changed by +executing commands within Edebug and there is no way to reset +the key sequence from Lisp. + +@item +Complex commands executed while in Edebug are added to the variable +@code{command-history}. In rare cases this can alter execution. + +@item +Within Edebug, the recursion depth appears one deeper than the recursion +depth outside Edebug. This is not true of the automatically updated +evaluation list window. + +@item +@code{standard-output} and @code{standard-input} are bound to @code{nil} +by the @code{recursive-edit}, but Edebug temporarily restores them during +evaluations. + +@item +The state of keyboard macro definition is saved and restored. While +Edebug is active, @code{defining-kbd-macro} is bound to +@code{edebug-continue-kbd-macro}. +@end itemize + +@node Instrumenting Macro Calls +@subsection Instrumenting Macro Calls + +When Edebug instruments an expression that calls a Lisp macro, it needs +additional advice to do the job properly. This is because there is no +way to tell which subexpressions of the macro call are forms to be +evaluated. (Evaluation may occur explicitly in the macro body, or when +the resulting expansion is evaluated, or any time later.) You must +explain the format of calls to each macro to enable Edebug to handle it. +To do this, use @code{def-edebug-form-spec} to define the format of +calls to a given macro. + +@deffn Macro def-edebug-spec macro specification +Specify which expressions of a call to macro @var{macro} are forms to be +evaluated. For simple macros, the @var{specification} often looks very +similar to the formal argument list of the macro definition, but +specifications are much more general than macro arguments. + +The @var{macro} argument may actually be any symbol, not just a macro +name. +@end deffn + +Here is a simple example that defines the specification for the +@code{for} macro described in the Emacs Lisp Reference Manual, followed +by an alternative, equivalent specification. + +@example +(def-edebug-spec for + (symbolp "from" form "to" form "do" &rest form)) + +(def-edebug-spec for + (symbolp ['from form] ['to form] ['do body])) +@end example + +Here is a table of the possibilities for @var{specification} and how each +directs processing of arguments. + +@table @bullet + +@item @code{t} +All arguments are instrumented for evaluation. + +@item @code{0} +None of the arguments is instrumented. + +@item a symbol +The symbol must have an Edebug specification which is used instead. +This indirection is repeated until another kind of specification is +found. This allows you to inherit the specification for another macro. + +@item a list +The elements of the list describe the types of the arguments of a +calling form. The possible elements of a specification list are +described in the following sections. +@end table + +@menu +* Specification List:: How to specify complex patterns of evaluation. +* Backtracking:: What Edebug does when matching fails. +@c * Debugging Backquote:: Debugging Backquote +* Specification Examples:: To help understand specifications. +@end menu + + +@node Specification List +@subsubsection Specification List + +@cindex Edebug specification list +A @dfn{specification list} is required for an Edebug specification if +some arguments of a macro call are evaluated while others are not. Some +elements in a specification list match one or more arguments, but others +modify the processing of all following elements. The latter, called +@dfn{specification keywords}, are symbols beginning with @samp{&} (such +as @code{&optional}). + +A specification list may contain sublists which match arguments that are +themselves lists, or it may contain vectors used for grouping. Sublists +and groups thus subdivide the specification list into a hierarchy of +levels. Specification keywords only apply to the remainder of the +sublist or group they are contained in. + +When a specification list involves alternatives or repetition, matching +it against an actual macro call may require backtracking. +@xref{Backtracking}, for more details. + +Edebug specifications provide the power of regular expression matching, +plus some context-free grammar constructs: the matching of sublists with +balanced parentheses, recursive processing of forms, and recursion via +indirect specifications. + +Here's a table of the possible elements of a specification list, with +their meanings: + +@table @code +@item sexp +A single unevaluated Lisp object object. + +@item form +A single evaluated expression, which is instrumented. + +@item place +@findex edebug-unwrap +A place to store a value, as in the Common Lisp @code{setf} construct. + +@item body +Short for @code{&rest form}. See @code{&rest} below. + +@item function-form +A function form: either a quoted function symbol, a quoted lambda +expression, or a form (that should evaluate to a function symbol or +lambda expression). This is useful when an argument that's a lambda +expression might be quoted with @code{quote} rather than +@code{function}, since it instruments the body of the lambda expression +either way. + +@item lambda-expr +A lambda expression with no quoting. + +@item &optional +@kindex &optional @r{(Edebug)} +All following elements in the specification list are optional; as soon +as one does not match, Edebug stops matching at this level. + +To make just a few elements optional followed by non-optional elements, +use @code{[&optional @var{specs}@dots{}]}. To specify that several +elements must all match or none, use @code{&optional +[@var{specs}@dots{}]}. See the @code{defun} example below. + +@item &rest +@kindex &rest @r{(Edebug)} +All following elements in the specification list are repeated zero or +more times. All the elements need not match in the last repetition, +however. + +To repeat only a few elements, use @code{[&rest @var{specs}@dots{}]}. +To specify several elements that must all match on every repetition, use +@code{&rest [@var{specs}@dots{}]}. + +@item &or +@kindex &or @r{(Edebug)} +Each of the following elements in the specification list is an +alternative. One of the alternatives must match, or the @code{&or} +specification fails. + +Each list element following @code{&or} is a single alternative. To +group two or more list elements as a single alternative, enclose them in +@code{[@dots{}]}. + +@item ¬ +@kindex ¬ @r{(Edebug)} +Each of the following elements is matched as alternatives as if by using +@code{&or}, but if any of them match, the specification fails. If none +of them match, nothing is matched, but the @code{¬} specification +succeeds. + +@item &define +@kindex &define @r{(Edebug)} +Indicates that the specification is for a defining form. The defining +form itself is not instrumented (i.e. Edebug does not stop before and +after the defining form), but forms inside it typically will be +instrumented. The @code{&define} keyword should be the first element in +a list specification. + +@item nil +This is successful when there are no more arguments to match at the +current argument list level; otherwise it fails. See sublist +specifications and the backquote example below. + +@item gate +@cindex preventing backtracking +No argument is matched but backtracking through the gate is disabled +while matching the remainder of the specifications at this level. This +is primarily used to generate more specific syntax error messages. See +@ref{Backtracking}, for more details. Also see the @code{let} example +below. + +@item @var{other-symbol} +@cindex indirect specifications +Any other symbol in a specification list may be a predicate or an +indirect specification. + +If the symbol has an Edebug specification, this @dfn{indirect +specification} should be either a list specification that is used in +place of the symbol, or a function that is called to process the +arguments. The specification may be defined with @code{def-edebug-spec} +just as for macros. See the @code{defun} example below. + +Otherwise, the symbol should be a predicate. The predicate is called +with the argument and the specification fails if the predicate returns +@code{nil}. In either case, that argument is not instrumented. + +@findex keywordp +@findex lambda-list-keywordp +Some suitable predicates include @code{symbolp}, @code{integerp}, +@code{stringp}, @code{vectorp}, and @code{atom}. +@ignore +, @code{keywordp}, and +@code{lambda-list-keywordp}. The last two, defined in @file{edebug.el}, +test whether the argument is a symbol starting with @samp{@code{:}} and +@samp{@code{&}} respectively. +@end ignore + +@item [@var{elements}@dots{}] +@cindex [@dots{}] (Edebug) +A vector of elements groups the elements into a single @dfn{group +specification}. Its meaning has nothing to do with vectors. + +@item "@var{string}" +The argument should be a symbol named @var{string}. This specification +is equivalent to the quoted symbol, @code{'@var{symbol}}, where the name +of @var{symbol} is the @var{string}, but the string form is preferred. + +@ignore +@item '@var{symbol} @r{or} (quote @var{symbol}) +The argument should be the symbol @var{symbol}. But use a string +specification instead. +@end ignore + +@item (vector @var{elements}@dots{}) +The argument should be a vector whose elements must match the +@var{elements} in the specification. See the backquote example below. + +@item (@var{elements}@dots{}) +Any other list is a @dfn{sublist specification} and the argument must be +a list whose elements match the specification @var{elements}. + +@cindex dotted lists (Edebug) +A sublist specification may be a dotted list and the corresponding list +argument may then be a dotted list. Alternatively, the last @sc{cdr} of a +dotted list specification may be another sublist specification (via a +grouping or an indirect specification, e.g. @code{(spec . [(more +specs@dots{})])}) whose elements match the non-dotted list arguments. +This is useful in recursive specifications such as in the backquote +example below. Also see the description of a @code{nil} specification +above for terminating such recursion. + +Note that a sublist specification of the form @code{(specs . nil)} +means the same as @code{(specs)}, and @code{(specs . +(sublist-elements@dots{}))} means the same as @code{(specs +sublist-elements@dots{})}. +@end table + +@c Need to document extensions with &symbol and :symbol + +Here is a list of additional specifications that may only appear after +@code{&define}. See the @code{defun} example below. + +@table @code +@item name +The argument, a symbol, is the name of the defining form. + +A defining form is not required to have a name field; and it may have +multiple name fields. + +@item :name +This construct does not actually match an argument. The element +following @code{:name} should be a symbol; it is used as an additional +name component for the definition. You can use this to add a unique, +static component to the name of the definition. It may be used more +than once. + +@item arg +The argument, a symbol, is the name of an argument of the defining form. +However, lambda list keywords (symbols starting with @samp{@code{&}}) +are not allowed. See @code{lambda-list} and the example below. + +@item lambda-list +@cindex lambda-list (Edebug) +This matches a lambda list---the argument list of a lambda expression. +The argument should be a list of symbols. + +@item def-body +The argument is the body of code in a definition. This is like +@code{body}, described above, but a definition body must be instrumented +with a different Edebug call that looks up information associated with +the definition. Use @code{def-body} for the highest level list of forms +within the definition. + +@item def-form +The argument is a single, highest-level form in a definition. This is +like @code{def-body}, except use this to match a single form rather than +a list of forms. As a special case, @code{def-form} also means that +tracing information is not output when the form is executed. See the +@code{interactive} example below. +@end table + +@node Backtracking +@subsubsection Backtracking + +@cindex backtracking +@cindex syntax error (Edebug) +If a specification fails to match at some point, this does not +necessarily mean a syntax error will be signaled; instead, +@dfn{backtracking} will take place until all alternatives have been +exhausted. Eventually every element of the argument list must be +matched by some element in the specification, and every required element +in the specification must match some argument. + +Backtracking is disabled for the remainder of a sublist or group when +certain conditions occur, described below. Backtracking is reenabled +when a new alternative is established by @code{&optional}, @code{&rest}, +or @code{&or}. It is also reenabled initially when processing a +sublist or group specification or an indirect specification. + +You might want to disable backtracking to commit to some alternative so +that Edebug can provide a more specific syntax error message. Normally, +if no alternative matches, Edebug reports that none matched, but if one +alternative is committed to, Edebug can report how it failed to match. + +First, backtracking is disabled while matching any of the form +specifications (i.e. @code{form}, @code{body}, @code{def-form}, and +@code{def-body}). These specifications will match any form so any error +must be in the form itself rather than at a higher level. + +Second, backtracking is disabled after successfully matching a quoted +symbol or string specification, since this usually indicates a +recognized construct. If you have a set of alternative constructs that +all begin with the same symbol, you can usually work around this +constraint by factoring the symbol out of the alternatives, e.g., +@code{["foo" &or [first case] [second case] ...]}. + +Third, backtracking may be explicitly disabled by using the +@code{gate} specification. This is useful when you know that +no higher alternatives may apply. + +@ignore +@node Debugging Backquote +@subsubsection Debugging Backquote + +@findex ` (Edebug) +@cindex backquote (Edebug) +Backquote (@kbd{`}) is a macro that results in an expression that may or +may not be evaluated. It is often used to simplify the definition of a +macro to return an expression to be evaluated, but Edebug cannot know +whether the resyult of backquote will be used in any other way. + +The forms inside unquotes (@code{,} and @code{,@@}) are evaluated, and +Edebug instruments them. + +Edebug supports nested backquotes, but there is a limit on the support +of quotes inside of backquotes. Forms quoted with @code{'} are not +normally evaluated, but if the quoted form appears immediately within +@code{,} and @code{,@@} forms, Edebug treats this as a backquoted form +at the next higher level (even if there is not a next higher level; this +is difficult to fix). + +@findex edebug-` +If the backquoted forms are code to be evaluated, you can have Edebug +instrument them by using @code{edebug-`} instead of the regular +@code{`}. Unquoting forms can be used inside @code{edebug-`} anywhere a +form is normally allowed. But @code{(, @var{form})} may be used in two +other places specially recognized by Edebug: wherever a predicate +specification would match, and at the head of a list form where the +function name normally appears. The @var{form} inside a spliced +unquote, @code{(,@@ @var{form})}, will be instrumented, but the unquote +form itself will not be instrumented since this would interfere with the +splicing. + +There is one other complication with using @code{edebug-`}. If the +@code{edebug-`} call is in a macro and the macro may be called from code +that is also instrumented, and if unquoted forms contain any macro +arguments bound to instrumented forms, then you should modify the +specification for the macro as follows: the specifications for those +arguments must use @code{def-form} instead of @code{form}. (This is to +reestablish the Edebugging context for those external forms.) + +For example, the @code{for} macro (@pxref{Problems with Macros,,, elisp, +Emacs Lisp Reference Manual}) is shown here but with @code{edebug-`} +substituted for regular @code{`}. + +@example +(defmacro inc (var) + (list 'setq var (list '1+ var))) + +(defmacro for (var from init to final do &rest body) + (let ((tempvar (make-symbol "max"))) + (edebug-` (let (((, var) (, init)) + ((, tempvar) (, final))) + (while (<= (, var) (, tempvar)) + (,@ body) + (inc (, var))))))) +@end example + +Here is the corresponding modified Edebug specification and a +call of the macro: + +@example +(def-edebug-spec for + (symbolp "from" def-form "to" def-form "do" &rest def-form)) + +(let ((n 5)) + (for i from n to (* n (+ n 1)) do + (message "%s" i))) +@end example + +After instrumenting the @code{for} macro and the macro call, Edebug +first steps to the beginning of the macro call, then into the macro +body, then through each of the unquoted expressions in the backquote +showing the expressions that will be embedded. Then when the macro +expansion is evaluated, Edebug will step through the @code{let} form and +each time it gets to an unquoted form, it will jump back to an argument +of the macro call to step through that expression. Finally stepping +will continue after the macro call. Even more convoluted execution +paths may result when using anonymous functions. + +@vindex edebug-unwrap-results +When the result of an expression is an instrumented expression, it is +difficult to see the expression inside the instrumentation. So +you may want to set the option @code{edebug-unwrap-results} to a +non-@code{nil} value while debugging such expressions, but it would slow +Edebug down to always do this. + +@end ignore +@node Specification Examples +@subsubsection Specification Examples + +It may be easier to understand Edebug specifications by studying +the examples provided here. + +A @code{let} special form has a sequence of bindings and a body. Each +of the bindings is either a symbol or a sublist with a symbol and +optional value. In the specification below, notice the @code{gate} +inside of the sublist to prevent backtracking once a sublist is found. + +@example +(def-edebug-spec let + ((&rest + &or symbolp (gate symbolp &optional form)) + body)) +@end example + +Edebug uses the following specifications for @code{defun} and +@code{defmacro} and the associated argument list and @code{interactive} +specifications. It is necessary to handle interactive forms specially +since an expression argument it is actually evaluated outside of the +function body. + +@example +(def-edebug-spec defmacro defun) ; @r{Indirect ref to @code{defun} spec} +(def-edebug-spec defun + (&define name lambda-list + [&optional stringp] ; @r{Match the doc string, if present.} + [&optional ("interactive" interactive)] + def-body)) + +(def-edebug-spec lambda-list + (([&rest arg] + [&optional ["&optional" arg &rest arg]] + &optional ["&rest" arg] + ))) + +(def-edebug-spec interactive + (&optional &or stringp def-form)) ; @r{Notice: @code{def-form}} +@end example + +The specification for backquote below illustrates how to match +dotted lists and use @code{nil} to terminate recursion. It also +illustrates how components of a vector may be matched. (The actual +specification defined by Edebug does not support dotted lists because +doing so causes very deep recursion that could fail.) + +@example +(def-edebug-spec ` (backquote-form)) ;; alias just for clarity + +(def-edebug-spec backquote-form + (&or ([&or "," ",@@"] &or ("quote" backquote-form) form) + (backquote-form . [&or nil backquote-form]) + (vector &rest backquote-form) + sexp)) +@end example + + +@node Edebug Options +@subsection Edebug Options + + These options affect the behavior of Edebug: + +@defopt edebug-setup-hook +Functions to call before Edebug is used. Each time it is set to a new +value, Edebug will call those functions once and then +@code{edebug-setup-hook} is reset to @code{nil}. You could use this to +load up Edebug specifications associated with a package you are using +but only when you also use Edebug. +@xref{Instrumenting}. +@end defopt + +@defopt edebug-all-defs +If this is non-@code{nil}, normal evaluation of defining forms such as +@code{defun} and @code{defmacro} instruments them for Edebug. This +applies to @code{eval-defun}, @code{eval-region}, and +@code{eval-current-buffer}. @xref{Instrumenting}. +@end defopt + +@defopt edebug-all-forms +If this is non-@code{nil}, the commands @code{eval-defun}, @code{eval-region}, +and @code{eval-current-buffer} instrument all forms, even those that +don't define anything. + +Use the command @kbd{M-x edebug-all-forms} to toggle the value of this +option. +@xref{Instrumenting}. +@end defopt + +@defopt edebug-save-windows +If this is non-@code{nil}, Edebug saves and restores the window +configuration. That takes some time, so if your program does not care +what happens to the window configurations, it is better to set this +variable to @code{nil}. + +If the value is a list, only the listed windows are saved and +restored. + +You can use the @kbd{W} command in Edebug to change this variable +interactively. @xref{Edebug Display Update}. +@end defopt + +@defopt edebug-save-displayed-buffer-points +If non-@code{nil}, Edebug saves and restores point in all buffers. + +Saving and restoring point in other buffers is necessary if you are +debugging code that changes the point of a buffer which is displayed in +a non-selected window. If Edebug or the user then selects the window, +the buffer's point will change to the window's point. + +Saving and restoring point in all buffers is expensive, since it +requires selecting each window twice, so enable this only if you need +it. @xref{Edebug Display Update}. +@end defopt + +@defopt edebug-initial-mode +If this variable is non-@code{nil}, it specifies the initial execution +mode for Edebug when it is first activated. Possible values are +@code{step}, @code{next}, @code{go}, @code{Go-nonstop}, @code{trace}, +@code{Trace-fast}, @code{continue}, and @code{Continue-fast}. + +The default value is @code{step}. +@xref{Edebug Execution Modes}. +@end defopt + +@defopt edebug-trace +@findex edebug-print-trace-before +@findex edebug-print-trace-after +Non-@code{nil} means display a trace of function entry and exit. +Tracing output is displayed in a buffer named @samp{*edebug-trace*}, one +function entry or exit per line, indented by the recursion level. + +The default value is @code{nil}. + +Also see @code{edebug-tracing}. +@xref{Tracing}. +@end defopt + +@defopt edebug-test-coverage +If non-@code{nil}, Edebug tests coverage of all expressions debugged. +This is done by comparing the result of each expression +with the previous result. Coverage is considered OK if two different +results are found. So to sufficiently test the coverage of your code, +try to execute it under conditions that evaluate all expressions more +than once, and produce different results for each expression. + +Use @kbd{M-x edebug-display-freq-count} to display the frequency count +and coverage information for a definition. +@xref{Coverage Testing}. +@end defopt + +@defopt edebug-continue-kbd-macro +If non-@code{nil}, continue defining or executing any keyboard macro +that is executing outside of Edebug. Use this with caution since it is not +debugged. +@xref{Edebug Execution Modes}. +@end defopt + +@defopt edebug-print-length +If non-@code{nil}, bind @code{print-length} to this while printing +results in Edebug. The default value is @code{50}. +@xref{Printing in Edebug}. +@end defopt + +@defopt edebug-print-level +If non-@code{nil}, bind @code{print-level} to this while printing +results in Edebug. The default value is @code{50}. +@end defopt + +@defopt edebug-print-circle +If non-@code{nil}, bind @code{print-circle} to this while printing +results in Edebug. The default value is @code{nil}. +@end defopt + +@defopt edebug-on-error +Edebug binds @code{debug-on-error} to this value, if +@code{debug-on-error} was previously @code{nil}. @xref{Trapping +Errors}. +@end defopt + +@defopt edebug-on-quit +Edebug binds @code{debug-on-quit} to this value, if +@code{debug-on-quit} was previously @code{nil}. @xref{Trapping +Errors}. +@end defopt + + If you change the values of @code{edebug-on-error} or +@code{edebug-on-quit} while Edebug is active, their values won't be used +until the @emph{next} time Edebug is invoked at a deeper command level. + +@ignore +@defopt edebug-unwrap-results +Non-@code{nil} if Edebug should unwrap results of expressions. This is +useful when debugging macros where the results of expressions are +instrumented expressions. But don't do this when results might be +circular, or an infinite loop will result. @xref{Debugging Backquote}. +@end defopt +@end ignore + +@defopt edebug-global-break-condition +If non-@code{nil}, an expression to test for at every stop point. +If the result is non-nil, then break. Errors are ignored. +@xref{Global Break Condition}. +@end defopt + 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 @@ +@c -*-texinfo-*- +@c This is part of the GNU Emacs Lisp Reference Manual. +@c Copyright (C) 1990, 1991, 1992, 1993, 1994 Free Software Foundation, Inc. +@c See the file elisp.texi for copying conditions. +@setfilename ../info/eval +@node Evaluation, Control Structures, Symbols, Top +@chapter Evaluation +@cindex evaluation +@cindex interpreter +@cindex interpreter +@cindex value of expression + + The @dfn{evaluation} of expressions in Emacs Lisp is performed by the +@dfn{Lisp interpreter}---a program that receives a Lisp object as input +and computes its @dfn{value as an expression}. How it does this depends +on the data type of the object, according to rules described in this +chapter. The interpreter runs automatically to evaluate portions of +your program, but can also be called explicitly via the Lisp primitive +function @code{eval}. + +@ifinfo +@menu +* Intro Eval:: Evaluation in the scheme of things. +* Eval:: How to invoke the Lisp interpreter explicitly. +* Forms:: How various sorts of objects are evaluated. +* Quoting:: Avoiding evaluation (to put constants in the program). +@end menu + +@node Intro Eval +@section Introduction to Evaluation + + The Lisp interpreter, or evaluator, is the program which computes +the value of an expression which is given to it. When a function +written in Lisp is called, the evaluator computes the value of the +function by evaluating the expressions in the function body. Thus, +running any Lisp program really means running the Lisp interpreter. + + How the evaluator handles an object depends primarily on the data +type of the object. +@end ifinfo + +@cindex forms +@cindex expression + A Lisp object which is intended for evaluation is called an +@dfn{expression} or a @dfn{form}. The fact that expressions are data +objects and not merely text is one of the fundamental differences +between Lisp-like languages and typical programming languages. Any +object can be evaluated, but in practice only numbers, symbols, lists +and strings are evaluated very often. + + It is very common to read a Lisp expression and then evaluate the +expression, but reading and evaluation are separate activities, and +either can be performed alone. Reading per se does not evaluate +anything; it converts the printed representation of a Lisp object to the +object itself. It is up to the caller of @code{read} whether this +object is a form to be evaluated, or serves some entirely different +purpose. @xref{Input Functions}. + + Do not confuse evaluation with command key interpretation. The +editor command loop translates keyboard input into a command (an +interactively callable function) using the active keymaps, and then +uses @code{call-interactively} to invoke the command. The execution of +the command itself involves evaluation if the command is written in +Lisp, but that is not a part of command key interpretation itself. +@xref{Command Loop}. + +@cindex recursive evaluation + Evaluation is a recursive process. That is, evaluation of a form may +call @code{eval} to evaluate parts of the form. For example, evaluation +of a function call first evaluates each argument of the function call, +and then evaluates each form in the function body. Consider evaluation +of the form @code{(car x)}: the subform @code{x} must first be evaluated +recursively, so that its value can be passed as an argument to the +function @code{car}. + +@cindex environment + The evaluation of forms takes place in a context called the +@dfn{environment}, which consists of the current values and bindings of +all Lisp variables.@footnote{This definition of ``environment'' is +specifically not intended to include all the data which can affect the +result of a program.} Whenever the form refers to a variable without +creating a new binding for it, the value of the binding in the current +environment is used. @xref{Variables}. + +@cindex side effect + Evaluation of a form may create new environments for recursive +evaluation by binding variables (@pxref{Local Variables}). These +environments are temporary and vanish by the time evaluation of the form +is complete. The form may also make changes that persist; these changes +are called @dfn{side effects}. An example of a form that produces side +effects is @code{(setq foo 1)}. + + Finally, evaluation of one particular function call, @code{byte-code}, +invokes the @dfn{byte-code interpreter} on its arguments. Although the +byte-code interpreter is not the same as the Lisp interpreter, it uses +the same environment as the Lisp interpreter, and may on occasion invoke +the Lisp interpreter. (@xref{Byte Compilation}.) + + The details of what evaluation means for each kind of form are +described below (@pxref{Forms}). + +@node Eval +@section Eval + + Most often, forms are evaluated automatically, by virtue of their +occurrence in a program being run. On rare occasions, you may need to +write code that evaluates a form that is computed at run time, such as +after reading a form from text being edited or getting one from a +property list. On these occasions, use the @code{eval} function. + + The functions and variables described in this section evaluate +forms, specify limits to the evaluation process, or record recently +returned values. Loading a file also does evaluation +(@pxref{Loading}). + +@defun eval form +This is the basic function for performing evaluation. It evaluates +@var{form} in the current environment and returns the result. How the +evaluation proceeds depends on the type of the object (@pxref{Forms}). + +Since @code{eval} is a function, the argument expression that appears +in a call to @code{eval} is evaluated twice: once as preparation before +@code{eval} is called, and again by the @code{eval} function itself. +Here is an example: + +@example +@group +(setq foo 'bar) + @result{} bar +@end group +@group +(setq bar 'baz) + @result{} baz +;; @r{@code{eval} receives argument @code{bar}, which is the value of @code{foo}} +(eval foo) + @result{} baz +@end group +@end example + +The number of currently active calls to @code{eval} is limited to +@code{max-lisp-eval-depth} (see below). +@end defun + +@cindex evaluation of buffer contents +@deffn Command eval-current-buffer &optional stream +This function evaluates the forms in the current buffer. It reads +forms from the buffer and calls @code{eval} on them until the end of the +buffer is reached, or until an error is signaled and not handled. + +If @var{stream} is supplied, the variable @code{standard-output} is +bound to @var{stream} during the evaluation (@pxref{Output +Functions}). + +@code{eval-current-buffer} always returns @code{nil}. +@end deffn + +@deffn Command eval-region start end &optional stream +This function evaluates the forms in the current buffer in the region +defined by the positions @var{start} and @var{end}. It reads forms from +the region and calls @code{eval} on them until the end of the region is +reached, or until an error is signaled and not handled. + +If @var{stream} is supplied, @code{standard-output} is bound to it +for the duration of the command. + +@code{eval-region} always returns @code{nil}. +@end deffn + +@defvar max-lisp-eval-depth +This variable defines the maximum depth allowed in calls to @code{eval}, +@code{apply}, and @code{funcall} before an error is signaled (with error +message @code{"Lisp nesting exceeds max-lisp-eval-depth"}). This counts +calling the functions mentioned in Lisp expression, and recursive +evaluation of function call arguments and function body forms. + +This limit, with the associated error when it is exceeded, is one way +that Lisp avoids infinite recursion on an ill-defined function. +@cindex Lisp nesting error + +The default value of this variable is 200. If you set it to a value +less than 100, Lisp will reset it to 100 if the given value is reached. + +@code{max-specpdl-size} provides another limit on nesting. +@xref{Local Variables}. +@end defvar + +@defvar values +The value of this variable is a list of the values returned by all the +expressions which were read from buffers (including the minibuffer), +evaluated, and printed. The elements are ordered most recent first. + +@example +@group +(setq x 1) + @result{} 1 +@end group +@group +(list 'A (1+ 2) auto-save-default) + @result{} (A 3 t) +@end group +@group +values + @result{} ((A 3 t) 1 @dots{}) +@end group +@end example + +This variable is useful for referring back to values of forms recently +evaluated. It is generally a bad idea to print the value of +@code{values} itself, since this may be very long. Instead, examine +particular elements, like this: + +@example +@group +;; @r{Refer to the most recent evaluation result.} +(nth 0 values) + @result{} (A 3 t) +@end group +@group +;; @r{That put a new element on,} +;; @r{so all elements move back one.} +(nth 1 values) + @result{} (A 3 t) +@end group +@group +;; @r{This gets the element that was next-to-last} +;; @r{before this example.} +(nth 3 values) + @result{} 1 +@end group +@end example +@end defvar + +@node Forms +@section Kinds of Forms + + A Lisp object that is intended to be evaluated is called a @dfn{form}. +How Emacs evaluates a form depends on its data type. Emacs has three +different kinds of form that are evaluated differently: symbols, lists, +and ``all other types''. This section describes all three kinds, +starting with ``all other types'' which are self-evaluating forms. + +@menu +* Self-Evaluating Forms:: Forms that evaluate to themselves. +* Symbol Forms:: Symbols evaluate as variables. +* Classifying Lists:: How to distinguish various sorts of list forms. +* Function Indirection:: When a symbol appears as the car of a list, + we find the real function via the symbol. +* Function Forms:: Forms that call functions. +* Macro Forms:: Forms that call macros. +* Special Forms:: ``Special forms'' are idiosyncratic primitives, + most of them extremely important. +* Autoloading:: Functions set up to load files + containing their real definitions. +@end menu + +@node Self-Evaluating Forms +@subsection Self-Evaluating Forms +@cindex vector evaluation +@cindex literal evaluation +@cindex self-evaluating form + + A @dfn{self-evaluating form} is any form that is not a list or symbol. +Self-evaluating forms evaluate to themselves: the result of evaluation +is the same object that was evaluated. Thus, the number 25 evaluates to +25, and the string @code{"foo"} evaluates to the string @code{"foo"}. +Likewise, evaluation of a vector does not cause evaluation of the +elements of the vector---it returns the same vector with its contents +unchanged. + +@example +@group +'123 ; @r{An object, shown without evaluation.} + @result{} 123 +@end group +@group +123 ; @r{Evaluated as usual---result is the same.} + @result{} 123 +@end group +@group +(eval '123) ; @r{Evaluated ``by hand''---result is the same.} + @result{} 123 +@end group +@group +(eval (eval '123)) ; @r{Evaluating twice changes nothing.} + @result{} 123 +@end group +@end example + + It is common to write numbers, characters, strings, and even vectors +in Lisp code, taking advantage of the fact that they self-evaluate. +However, it is quite unusual to do this for types that lack a read +syntax, because there's no way to write them textually; however, it is +possible to construct Lisp expressions containing these types by means +of a Lisp program. Here is an example: + +@example +@group +;; @r{Build an expression containing a buffer object.} +(setq buffer (list 'print (current-buffer))) + @result{} (print #<buffer eval.texi>) +@end group +@group +;; @r{Evaluate it.} +(eval buffer) + @print{} #<buffer eval.texi> + @result{} #<buffer eval.texi> +@end group +@end example + +@node Symbol Forms +@subsection Symbol Forms +@cindex symbol evaluation + + When a symbol is evaluated, it is treated as a variable. The result +is the variable's value, if it has one. If it has none (if its value +cell is void), an error is signaled. For more information on the use of +variables, see @ref{Variables}. + + In the following example, we set the value of a symbol with +@code{setq}. Then we evaluate the symbol, and get back the value that +@code{setq} stored. + +@example +@group +(setq a 123) + @result{} 123 +@end group +@group +(eval 'a) + @result{} 123 +@end group +@group +a + @result{} 123 +@end group +@end example + + The symbols @code{nil} and @code{t} are treated specially, so that the +value of @code{nil} is always @code{nil}, and the value of @code{t} is +always @code{t}. Thus, these two symbols act like self-evaluating +forms, even though @code{eval} treats them like any other symbol. + +@node Classifying Lists +@subsection Classification of List Forms +@cindex list form evaluation + + A form that is a nonempty list is either a function call, a macro +call, or a special form, according to its first element. These three +kinds of forms are evaluated in different ways, described below. The +remaining list elements constitute the @dfn{arguments} for the function, +macro, or special form. + + The first step in evaluating a nonempty list is to examine its first +element. This element alone determines what kind of form the list is +and how the rest of the list is to be processed. The first element is +@emph{not} evaluated, as it would be in some Lisp dialects such as +Scheme. + +@node Function Indirection +@subsection Symbol Function Indirection +@cindex symbol function indirection +@cindex indirection +@cindex void function + + If the first element of the list is a symbol then evaluation examines +the symbol's function cell, and uses its contents instead of the +original symbol. If the contents are another symbol, this process, +called @dfn{symbol function indirection}, is repeated until it obtains a +non-symbol. @xref{Function Names}, for more information about using a +symbol as a name for a function stored in the function cell of the +symbol. + + One possible consequence of this process is an infinite loop, in the +event that a symbol's function cell refers to the same symbol. Or a +symbol may have a void function cell, in which case the subroutine +@code{symbol-function} signals a @code{void-function} error. But if +neither of these things happens, we eventually obtain a non-symbol, +which ought to be a function or other suitable object. + +@kindex invalid-function +@cindex invalid function + More precisely, we should now have a Lisp function (a lambda +expression), a byte-code function, a primitive function, a Lisp macro, a +special form, or an autoload object. Each of these types is a case +described in one of the following sections. If the object is not one of +these types, the error @code{invalid-function} is signaled. + + The following example illustrates the symbol indirection process. We +use @code{fset} to set the function cell of a symbol and +@code{symbol-function} to get the function cell contents +(@pxref{Function Cells}). Specifically, we store the symbol @code{car} +into the function cell of @code{first}, and the symbol @code{first} into +the function cell of @code{erste}. + +@smallexample +@group +;; @r{Build this function cell linkage:} +;; ------------- ----- ------- ------- +;; | #<subr car> | <-- | car | <-- | first | <-- | erste | +;; ------------- ----- ------- ------- +@end group +@end smallexample + +@smallexample +@group +(symbol-function 'car) + @result{} #<subr car> +@end group +@group +(fset 'first 'car) + @result{} car +@end group +@group +(fset 'erste 'first) + @result{} first +@end group +@group +(erste '(1 2 3)) ; @r{Call the function referenced by @code{erste}.} + @result{} 1 +@end group +@end smallexample + + By contrast, the following example calls a function without any symbol +function indirection, because the first element is an anonymous Lisp +function, not a symbol. + +@smallexample +@group +((lambda (arg) (erste arg)) + '(1 2 3)) + @result{} 1 +@end group +@end smallexample + +@noindent +After that function is called, its body is evaluated; this does +involve symbol function indirection when calling @code{erste}. + + The built-in function @code{indirect-function} provides an easy way to +perform symbol function indirection explicitly. + +@c Emacs 19 feature +@defun indirect-function function +This function returns the meaning of @var{function} as a function. If +@var{function} is a symbol, then it finds @var{function}'s function +definition and starts over with that value. If @var{function} is not a +symbol, then it returns @var{function} itself. + +Here is how you could define @code{indirect-function} in Lisp: + +@smallexample +(defun indirect-function (function) + (if (symbolp function) + (indirect-function (symbol-function function)) + function)) +@end smallexample +@end defun + +@node Function Forms +@subsection Evaluation of Function Forms +@cindex function form evaluation +@cindex function call + + If the first element of a list being evaluated is a Lisp function +object, byte-code object or primitive function object, then that list is +a @dfn{function call}. For example, here is a call to the function +@code{+}: + +@example +(+ 1 x) +@end example + + The first step ni evaluating a function call is to evaluate the +remaining elements of the list in the order they appear. The results +are the actual argument values, one value for each list element. The +next step is to call the function with this list of arguments, +effectively using the function @code{apply} (@pxref{Calling Functions}). +If the function is written in Lisp, the arguments are used to bind the +argument variables of the function (@pxref{Lambda Expressions}); then +the forms in the function body are evaluated in order, and the value of +the last body form becomes the value of the function call. + +@node Macro Forms +@subsection Lisp Macro Evaluation +@cindex macro call evaluation + + If the first element of a list being evaluated is a macro object, then +the list is a @dfn{macro call}. When a macro call is evaluated, the +elements of the rest of the list are @emph{not} initially evaluated. +Instead, these elements themselves are used as the arguments of the +macro. The macro definition computes a replacement form, called the +@dfn{expansion} of the macro, to be evaluated in place of the original +form. The expansion may be any sort of form: a self-evaluating +constant, a symbol or a list. If the expansion is itself a macro call, +this process of expansion repeats until some other sort of form results. + + Normally, the argument expressions are not evaluated as part of +computing the macro expansion, but instead appear as part of the +expansion, so they are evaluated when the expansion is evaluated. + + For example, given a macro defined as follows: + +@example +@group +(defmacro cadr (x) + (list 'car (list 'cdr x))) +@end group +@end example + +@noindent +an expression such as @code{(cadr (assq 'handler list))} is a macro +call, and its expansion is: + +@example +(car (cdr (assq 'handler list))) +@end example + +@noindent +Note that the argument @code{(assq 'handler list)} appears in the +expansion. + +@xref{Macros}, for a complete description of Emacs Lisp macros. + +@node Special Forms +@subsection Special Forms +@cindex special form evaluation + + A @dfn{special form} is a primitive function specially marked so that +its arguments are not all evaluated. Most special forms define control +structures or perform variable bindings---things which functions cannot +do. + + Each special form has its own rules for which arguments are evaluated +and which are used without evaluation. Whether a particular argument is +evaluated may depend on the results of evaluating other arguments. + + Here is a list, in alphabetical order, of all of the special forms in +Emacs Lisp with a reference to where each is described. + +@table @code +@item and +@pxref{Combining Conditions} + +@item catch +@pxref{Catch and Throw} + +@item cond +@pxref{Conditionals} + +@item condition-case +@pxref{Handling Errors} + +@item defconst +@pxref{Defining Variables} + +@item defmacro +@pxref{Defining Macros} + +@item defun +@pxref{Defining Functions} + +@item defvar +@pxref{Defining Variables} + +@item function +@pxref{Anonymous Functions} + +@item if +@pxref{Conditionals} + +@item interactive +@pxref{Interactive Call} + +@item let +@itemx let* +@pxref{Local Variables} + +@item or +@pxref{Combining Conditions} + +@item prog1 +@itemx prog2 +@itemx progn +@pxref{Sequencing} + +@item quote +@pxref{Quoting} + +@item save-excursion +@pxref{Excursions} + +@item save-restriction +@pxref{Narrowing} + +@item save-window-excursion +@pxref{Window Configurations} + +@item setq +@pxref{Setting Variables} + +@item setq-default +@pxref{Creating Buffer-Local} + +@item track-mouse +@pxref{Mouse Tracking} + +@item unwind-protect +@pxref{Nonlocal Exits} + +@item while +@pxref{Iteration} + +@item with-output-to-temp-buffer +@pxref{Temporary Displays} +@end table + +@cindex CL note---special forms compared +@quotation +@b{Common Lisp note:} here are some comparisons of special forms in +GNU Emacs Lisp and Common Lisp. @code{setq}, @code{if}, and +@code{catch} are special forms in both Emacs Lisp and Common Lisp. +@code{defun} is a special form in Emacs Lisp, but a macro in Common +Lisp. @code{save-excursion} is a special form in Emacs Lisp, but +doesn't exist in Common Lisp. @code{throw} is a special form in +Common Lisp (because it must be able to throw multiple values), but it +is a function in Emacs Lisp (which doesn't have multiple +values).@refill +@end quotation + +@node Autoloading +@subsection Autoloading + + The @dfn{autoload} feature allows you to call a function or macro +whose function definition has not yet been loaded into Emacs. It +specifies which file contains the definition. When an autoload object +appears as a symbol's function definition, calling that symbol as a +function automatically loads the specified file; then it calls the real +definition loaded from that file. @xref{Autoload}. + +@node Quoting +@section Quoting +@cindex quoting + + The special form @code{quote} returns its single argument +``unchanged''. + +@defspec quote object +This special form returns @var{object}, without evaluating it. This +provides a way to include constant symbols and lists, which are not +self-evaluating objects, in a program. (It is not necessary to quote +self-evaluating objects such as numbers, strings, and vectors.) + +@cindex @samp{'} for quoting +@cindex quoting using apostrophe +@cindex apostrophe for quoting +Because @code{quote} is used so often in programs, Lisp provides a +convenient read syntax for it. An apostrophe character (@samp{'}) +followed by a Lisp object (in read syntax) expands to a list whose first +element is @code{quote}, and whose second element is the object. Thus, +the read syntax @code{'x} is an abbreviation for @code{(quote x)}. + +Here are some examples of expressions that use @code{quote}: + +@example +@group +(quote (+ 1 2)) + @result{} (+ 1 2) +@end group +@group +(quote foo) + @result{} foo +@end group +@group +'foo + @result{} foo +@end group +@group +''foo + @result{} (quote foo) +@end group +@group +'(quote foo) + @result{} (quote foo) +@end group +@group +['foo] + @result{} [(quote foo)] +@end group +@end example +@end defspec + + Other quoting constructs include @code{function} (@pxref{Anonymous +Functions}), which causes an anonymous lambda expression written in Lisp +to be compiled, and @code{`} (@pxref{Backquote}), which is used to quote +only 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 @@ +@c -*-texinfo-*- +@c This is part of the GNU Emacs Lisp Reference Manual. +@c Copyright (C) 1990, 1991, 1992, 1993, 1994 Free Software Foundation, Inc. +@c See the file elisp.texi for copying conditions. +@setfilename ../info/keymaps +@node Keymaps, Modes, Command Loop, Top +@chapter Keymaps +@cindex keymap + + The bindings between input events and commands are recorded in data +structures called @dfn{keymaps}. Each binding in a keymap associates +(or @dfn{binds}) an individual event type either with another keymap or +with a command. When an event is bound to a keymap, that keymap is +used to look up the next input event; this continues until a command +is found. The whole process is called @dfn{key lookup}. + +@menu +* Keymap Terminology:: Definitions of terms pertaining to keymaps. +* Format of Keymaps:: What a keymap looks like as a Lisp object. +* Creating Keymaps:: Functions to create and copy keymaps. +* Inheritance and Keymaps:: How one keymap can inherit the bindings + of another keymap. +* Prefix Keys:: Defining a key with a keymap as its definition. +* Menu Keymaps:: A keymap can define a menu. +* Active Keymaps:: Each buffer has a local keymap + to override the standard (global) bindings. + A minor mode can also override them. +* Key Lookup:: How extracting elements from keymaps works. +* Functions for Key Lookup:: How to request key lookup. +* Changing Key Bindings:: Redefining a key in a keymap. +* Key Binding Commands:: Interactive interfaces for redefining keys. +* Scanning Keymaps:: Looking through all keymaps, for printing help. +@end menu + +@node Keymap Terminology +@section Keymap Terminology +@cindex key +@cindex keystroke +@cindex key binding +@cindex binding of a key +@cindex complete key +@cindex undefined key + + A @dfn{keymap} is a table mapping event types to definitions (which +can be any Lisp objects, though only certain types are meaningful for +execution by the command loop). Given an event (or an event type) and a +keymap, Emacs can get the event's definition. Events include ordinary +@sc{ASCII} characters, function keys, and mouse actions (@pxref{Input +Events}). + + A sequence of input events that form a unit is called a +@dfn{key sequence}, or @dfn{key} for short. A sequence of one event +is always a key sequence, and so are some multi-event sequences. + + A keymap determines a binding or definition for any key sequence. If +the key sequence is a single event, its binding is the definition of the +event in the keymap. The binding of a key sequence of more than one +event is found by an iterative process: the binding of the first event +is found, and must be a keymap; then the second event's binding is found +in that keymap, and so on until all the events in the key sequence are +used up. + + If the binding of a key sequence is a keymap, we call the key sequence +a @dfn{prefix key}. Otherwise, we call it a @dfn{complete key} (because +no more characters can be added to it). If the binding is @code{nil}, +we call the key @dfn{undefined}. Examples of prefix keys are @kbd{C-c}, +@kbd{C-x}, and @kbd{C-x 4}. Examples of defined complete keys are +@kbd{X}, @key{RET}, and @kbd{C-x 4 C-f}. Examples of undefined complete +keys are @kbd{C-x C-g}, and @kbd{C-c 3}. @xref{Prefix Keys}, for more +details. + + The rule for finding the binding of a key sequence assumes that the +intermediate bindings (found for the events before the last) are all +keymaps; if this is not so, the sequence of events does not form a +unit---it is not really a key sequence. In other words, removing one or +more events from the end of any valid key must always yield a prefix +key. For example, @kbd{C-f C-f} is not a key; @kbd{C-f} is not a prefix +key, so a longer sequence starting with @kbd{C-f} cannot be a key. + + Note that the set of possible multi-event key sequences depends on the +bindings for prefix keys; therefore, it can be different for different +keymaps, and can change when bindings are changed. However, a one-event +sequence is always a key sequence, because it does not depend on any +prefix keys for its well-formedness. + + At any time, several primary keymaps are @dfn{active}---that is, in +use for finding key bindings. These are the @dfn{global map}, which is +shared by all buffers; the @dfn{local keymap}, which is usually +associated with a specific major mode; and zero or more @dfn{minor mode +keymaps} which belong to currently enabled minor modes. (Not all minor +modes have keymaps.) The local keymap bindings shadow (i.e., take +precedence over) the corresponding global bindings. The minor mode +keymaps shadow both local and global keymaps. @xref{Active Keymaps}, +for details. + +@node Format of Keymaps +@section Format of Keymaps +@cindex format of keymaps +@cindex keymap format +@cindex full keymap +@cindex sparse keymap + + A keymap is a list whose @sc{car} is the symbol @code{keymap}. The +remaining elements of the list define the key bindings of the keymap. +Use the function @code{keymapp} (see below) to test whether an object is +a keymap. + + An ordinary element is a cons cell of the form @code{(@var{type} .@: +@var{binding})}. This specifies one binding which applies to events of +type @var{type}. Each ordinary binding applies to events of a +particular @dfn{event type}, which is always a character or a symbol. +@xref{Classifying Events}. + +@cindex default key binding +@c Emacs 19 feature + A cons cell whose @sc{car} is @code{t} is a @dfn{default key binding}; +any event not bound by other elements of the keymap is given +@var{binding} as its binding. Default bindings allow a keymap to bind +all possible event types without having to enumerate all of them. A +keymap that has a default binding completely masks any lower-precedence +keymap. + + If an element of a keymap is a vector, the vector counts as bindings +for all the @sc{ASCII} characters; vector element @var{n} is the binding +for the character with code @var{n}. This is a more compact way to +record lots of bindings. A keymap with such a vector is called a +@dfn{full keymap}. Other keymaps are called @dfn{sparse keymaps}. + + When a keymap contains a vector, it always defines a binding for every +@sc{ASCII} character even if the vector element is @code{nil}. Such a +binding of @code{nil} overrides any default binding in the keymap. +However, default bindings are still meaningful for events that are not +@sc{ASCII} characters. A binding of @code{nil} does @emph{not} +override lower-precedence keymaps; thus, if the local map gives a +binding of @code{nil}, Emacs uses the binding from the global map. + +@cindex keymap prompt string +@cindex overall prompt string +@cindex prompt string of keymap + Aside from bindings, a keymap can also have a string as an element. +This is called the @dfn{overall prompt string} and makes it possible to +use the keymap as a menu. @xref{Menu Keymaps}. + +@cindex meta characters lookup + Keymaps do not directly record bindings for the meta characters, whose +codes are from 128 to 255. Instead, meta characters are regarded for +purposes of key lookup as sequences of two characters, the first of +which is @key{ESC} (or whatever is currently the value of +@code{meta-prefix-char}). Thus, the key @kbd{M-a} is really represented +as @kbd{@key{ESC} a}, and its global binding is found at the slot for +@kbd{a} in @code{esc-map} (@pxref{Prefix Keys}). + + Here as an example is the local keymap for Lisp mode, a sparse +keymap. It defines bindings for @key{DEL} and @key{TAB}, plus @kbd{C-c +C-l}, @kbd{M-C-q}, and @kbd{M-C-x}. + +@example +@group +lisp-mode-map +@result{} +@end group +@group +(keymap + ;; @key{TAB} + (9 . lisp-indent-line) +@end group +@group + ;; @key{DEL} + (127 . backward-delete-char-untabify) +@end group +@group + (3 keymap + ;; @kbd{C-c C-l} + (12 . run-lisp)) +@end group +@group + (27 keymap + ;; @r{@kbd{M-C-q}, treated as @kbd{@key{ESC} C-q}} + (17 . indent-sexp) + ;; @r{@kbd{M-C-x}, treated as @kbd{@key{ESC} C-x}} + (24 . lisp-send-defun))) +@end group +@end example + +@defun keymapp object +This function returns @code{t} if @var{object} is a keymap, @code{nil} +otherwise. Practically speaking, this function tests for a list whose +@sc{car} is @code{keymap}. + +@example +@group +(keymapp '(keymap)) + @result{} t +@end group +@group +(keymapp (current-global-map)) + @result{} t +@end group +@end example +@end defun + +@node Creating Keymaps +@section Creating Keymaps +@cindex creating keymaps + + Here we describe the functions for creating keymaps. + +@defun make-keymap &optional prompt +This function creates and returns a new full keymap (i.e., one which +contains a vector of length 128 for defining all the @sc{ASCII} +characters). The new keymap initially binds all @sc{ASCII} characters +to @code{nil}, and does not bind any other kind of event. + +@example +@group +(make-keymap) + @result{} (keymap [nil nil nil @dots{} nil nil]) +@end group +@end example + +If you specify @var{prompt}, that becomes the overall prompt string for +the keymap. The prompt string is useful for menu keymaps (@pxref{Menu +Keymaps}). +@end defun + +@defun make-sparse-keymap &optional prompt +This function creates and returns a new sparse keymap with no entries. +The new keymap does not bind any events. The argument @var{prompt} +specifies a prompt string, as in @code{make-keymap}. + +@example +@group +(make-sparse-keymap) + @result{} (keymap) +@end group +@end example +@end defun + +@defun copy-keymap keymap +This function returns a copy of @var{keymap}. Any keymaps which +appear directly as bindings in @var{keymap} are also copied recursively, +and so on to any number of levels. However, recursive copying does not +take place when the definition of a character is a symbol whose function +definition is a keymap; the same symbol appears in the new copy. +@c Emacs 19 feature + +@example +@group +(setq map (copy-keymap (current-local-map))) +@result{} (keymap +@end group +@group + ;; @r{(This implements meta characters.)} + (27 keymap + (83 . center-paragraph) + (115 . center-line)) + (9 . tab-to-tab-stop)) +@end group + +@group +(eq map (current-local-map)) + @result{} nil +@end group +@group +(equal map (current-local-map)) + @result{} t +@end group +@end example +@end defun + +@node Inheritance and Keymaps +@section Inheritance and Keymaps +@cindex keymap inheritance +@cindex inheriting a keymap's bindings + + A keymap can inherit the bindings of another keymap. Do do this, make +a keymap whose ``tail'' is another existing keymap to inherit from. +Such a keymap looks like this: + +@example +(keymap @var{bindings}@dots{} . @var{other-keymap}) +@end example + +@noindent +The effect is that this keymap inherits all the bindings of +@var{other-keymap}, whatever they may be at the time a key is looked up, +but can add to them or override them with @var{bindings}. + +If you change the bindings in @var{other-keymap} using @code{define-key} +or other key-binding functions, these changes are visible in the +inheriting keymap unless shadowed by @var{bindings}. The converse is +not true: if you use @code{define-key} to change the inheriting keymap, +that affects @var{bindings}, but has no effect on @var{other-keymap}. + +Here is an example showing how to make a keymap that inherits +from @code{text-mode-map}: + +@example +(setq my-mode-map (cons 'keymap text-mode-map)) +@end example + +@node Prefix Keys +@section Prefix Keys +@cindex prefix key + + A @dfn{prefix key} has an associated keymap which defines what to do +with key sequences that start with the prefix key. For example, +@kbd{C-x} is a prefix key, and it uses a keymap which is also stored in +the variable @code{ctl-x-map}. Here is a list of the standard prefix +keys of Emacs and their keymaps: + +@itemize @bullet +@item +@vindex esc-map +@findex ESC-prefix +@code{esc-map} is used for events that follow @key{ESC}. Thus, the +global definitions of all meta characters are actually found here. This +map is also the function definition of @code{ESC-prefix}. + +@item +@cindex @kbd{C-h} +@code{help-map} is used for events that follow @kbd{C-h}. + +@item +@cindex @kbd{C-c} +@vindex mode-specific-map +@code{mode-specific-map} is for events that follow @kbd{C-c}. This +map is not actually mode specific; its name was chosen to be informative +for the user in @kbd{C-h b} (@code{display-bindings}), where it +describes the main use of the @kbd{C-c} prefix key. + +@item +@cindex @kbd{C-x} +@vindex ctl-x-map +@findex Control-X-prefix +@code{ctl-x-map} is the variable name for the map used for events +that follow @kbd{C-x}. This map is also the function definition of +@code{Control-X-prefix}. + +@item +@cindex @kbd{C-x 4} +@vindex ctl-x-4-map +@code{ctl-x-4-map} is used for events that follow @kbd{C-x 4}. + +@c Emacs 19 feature +@item +@cindex @kbd{C-x 5} +@vindex ctl-x-5-map +@code{ctl-x-5-map} used is for events that follow @kbd{C-x 5}. + +@c Emacs 19 feature +@item +@cindex @kbd{C-x n} +@cindex @kbd{C-x r} +@cindex @kbd{C-x a} +The prefix keys @kbd{C-x n}, @kbd{C-x r} and @kbd{C-x a} use keymaps +that have no special name. +@end itemize + + The binding of a prefix key is the keymap to use for looking up the +events that follow the prefix key. (It may instead be a symbol whose +function definition is a keymap. The effect is the same, but the symbol +serves as a name for the prefix key.) Thus, the binding of @kbd{C-x} is +the symbol @code{Control-X-prefix}, whose function definition is the +keymap for @kbd{C-x} commands. (The same keymap is also the value of +@code{ctl-x-map}.) + + Prefix key definitions of this sort can appear in any active keymap. +The definitions of @kbd{C-c}, @kbd{C-x}, @kbd{C-h} and @key{ESC} as +prefix keys appear in the global map, so these prefix keys are always +available. Major and minor modes can redefine a key as a prefix by +putting a prefix key definition for it in the local map or the minor +mode's map. @xref{Active Keymaps}. + + If a key is defined as a prefix in more than one active map, then its +various definitions are in effect merged: the commands defined in the +minor mode keymaps come first, followed by those in the local map's +prefix definition, and then by those from the global map. + + In the following example, we make @kbd{C-p} a prefix key in the local +keymap, in such a way that @kbd{C-p} is identical to @kbd{C-x}. Then +the binding for @kbd{C-p C-f} is the function @code{find-file}, just +like @kbd{C-x C-f}. The key sequence @kbd{C-p 6} is not found in any +active keymap. + +@example +@group +(use-local-map (make-sparse-keymap)) + @result{} nil +@end group +@group +(local-set-key "\C-p" ctl-x-map) + @result{} nil +@end group +@group +(key-binding "\C-p\C-f") + @result{} find-file +@end group + +@group +(key-binding "\C-p6") + @result{} nil +@end group +@end example + +@defun define-prefix-command symbol +@cindex prefix command + This function defines @var{symbol} as a prefix command: it creates a +full keymap and stores it as @var{symbol}'s function definition. +Storing the symbol as the binding of a key makes the key a prefix key +which has a name. It also sets @var{symbol} as a variable, to have the +keymap as its value. The function returns @var{symbol}. + + In Emacs version 18, only the function definition of @var{symbol} was +set, not the value as a variable. +@end defun + +@node Menu Keymaps +@section Menu Keymaps +@cindex menu keymaps + +@c Emacs 19 feature +A keymap can define a menu as well as bindings for keyboard keys and +mouse button. Menus are usually actuated with the mouse, but they can +work with the keyboard also. + +@menu +* Defining Menus:: How to make a keymap that defines a menu. +* Mouse Menus:: How users actuate the menu with the mouse. +* Keyboard Menus:: How they actuate it with the keyboard. +* Menu Example:: Making a simple menu. +* Menu Bar:: How to customize the menu bar. +* Modifying Menus:: How to add new items to a menu. +@end menu + +@node Defining Menus +@subsection Defining Menus +@cindex defining menus +@cindex menu prompt string +@cindex prompt string (of menu) + +A keymap is suitable for menu use if it has an @dfn{overall prompt +string}, which is a string that appears as an element of the keymap. +(@xref{Format of Keymaps}.) The string should describe the purpose of +the menu. The easiest way to construct a keymap with a prompt string is +to specify the string as an argument when you call @code{make-keymap} or +@code{make-sparse-keymap} (@pxref{Creating Keymaps}). + +The individual bindings in the menu keymap should have item +strings; these strings become the items displayed in the menu. A +binding with a item string looks like this: + +@example +(@var{string} . @var{real-binding}) +@end example + +The item string for a binding should be short---one or two words. It +should describe the action of the command it corresponds to. + +As far as @code{define-key} is concerned, @var{string} is part of the +event's binding. However, @code{lookup-key} returns just +@var{real-binding}, and only @var{real-binding} is used for executing +the key. + +You can also supply a second string, called the help string, as follows: + +@example +(@var{string} @var{help-string} . @var{real-binding}) +@end example + +Currently Emacs does not actually use @var{help-string}; it knows only +how to ignore @var{help-string} in order to extract @var{real-binding}. +In the future we hope to make @var{help-string} serve as extended +documentation for the menu item, available on request. + +If @var{real-binding} is @code{nil}, then @var{string} appears in the +menu but cannot be selected. + +If @var{real-binding} is a symbol, and has a non-@code{nil} +@code{menu-enable} property, that property is an expression which +controls whether the menu item is enabled. Every time the keymap is +used to display a menu, Emacs evaluates the expression, and it enables +the menu item only if the expression's value is non-@code{nil}. When a +menu item is disabled, it is displayed in a ``fuzzy'' fashion, and +cannot be selected with the mouse. + +The order of items in the menu is the same as the order of bindings in +the keymap. Since @code{define-key} puts new bindings at the front, you +should define the menu items starting at the bottom of the menu and +moving to the top, if you care about the order. When you add an item to +an existing menu, you can specify its position in the menu using +@code{define-key-after} (@pxref{Modifying Menus}). + +You've probably noticed that menu items show the equivalent keyboard key +sequence (if any) to invoke the same command. To save time on +recalculation, menu display caches this information in a sublist in the +binding, like this: + +@c This line is not too long--rms. +@example +(@var{string} @r{[}@var{help-string}@r{]} (@var{key-binding-data}) . @var{real-binding}) +@end example + +Don't put these sublists in the menu item yourself; menu display +calculates them automatically. Don't add keyboard equivalents to the +item string yourself, for that is redundant. + +@node Mouse Menus +@subsection Menus and the Mouse + +The way to make a menu keymap produce a menu is to make it the +definition of a prefix key. + +If the prefix key ends with a mouse event, Emacs handles the menu keymap +by popping up a visible menu, so that the user can select a choice with +the mouse. When the user clicks on a menu item, the event generated is +whatever character or symbol has the binding which brought about that +menu item. (A menu item may generate a series of events if the menu has +multiple levels or comes from the menu bar.) + +It's often best to use a button-down event to trigger the menu. Then +the user can select a menu item by releasing the button. + +A single keymap can appear as multiple menu panes, if you explicitly +arrange for this. The way to do this is to make a keymap for each pane, +then create a binding for each of those maps in the main keymap of the +menu. Give each of these bindings a item string that starts with +@samp{@@}. The rest of the item string becomes the name of the pane. +See the file @file{lisp/mouse.el} for an example of this. Any ordinary +bindings with @samp{@@}-less item strings are grouped into one pane, +which appears along with the other panes explicitly created for the +submaps. + +X toolkit menus don't have panes; instead, they can have submenus. +Every nested keymap becomes a submenu, whether the item string starts +with @samp{@@} or not. In a toolkit version of Emacs, The only thing +special about @samp{@@} at the beginning of an item string is that the +@samp{@@} doesn't appear in the menu item. + +You can also get multiple panes from separate keymaps. The full +definition of a prefix key always comes from merging the definitions +supplied by the various active keymaps (minor mode, local, and +global). When more than one of these keymaps is a menu, each of them +makes a separate pane or panes. @xref{Active Keymaps}. + +In toolkit versions of Emacs, menus don't have panes, so submenus are +used to represent the separate keymaps. Each keymap's contribution +becomes one submenu. + +A Lisp program can explicitly pop up a menu and receive the user's +choice. You can use keymaps for this also. @xref{Pop-Up Menus}. + +@node Keyboard Menus +@subsection Menus and the Keyboard + +When a prefix key ending with a keyboard event (a character or function +key) has a definition that is a menu keymap, the user can use the +keyboard to choose a menu item. + +Emacs displays the menu alternatives (the item strings of the +bindings) in the echo area. If they don't all fit at once, the user can +type @key{SPC} to see the next line of alternatives. Successive uses of +@key{SPC} eventually get to the end of the menu and then cycle around to +the beginning. + +When the user has found the desired alternative from the menu, he or she +should type the corresponding character---the one whose binding is that +alternative. + +In a menu intended for keyboard use, each menu item must clearly +indicate what character to type. The best convention to use is to make +the character the first letter of the item string. That is something +users will understand without being told. + +This way of using menus in an Emacs-like editor was inspired by the +Hierarkey system. + +@defvar menu-prompt-more-char +This variable specifies the character to use to ask to see +the next line of a menu. Its initial value is 32, the code +for @key{SPC}. +@end defvar + +@node Menu Example +@subsection Menu Example + + Here is a simple example of how to set up a menu for mouse use. + +@example +(defvar my-menu-map + (make-sparse-keymap "Key Commands <==> Functions")) +(fset 'help-for-keys my-menu-map) + +(define-key my-menu-map [bindings] + '("List all keystroke commands" . describe-bindings)) +(define-key my-menu-map [key] + '("Describe key briefly" . describe-key-briefly)) +(define-key my-menu-map [key-verbose] + '("Describe key verbose" . describe-key)) +(define-key my-menu-map [function] + '("Describe Lisp function" . describe-function)) +(define-key my-menu-map [where-is] + '("Where is this command" . where-is)) + +(define-key global-map [C-S-down-mouse-1] 'help-for-keys) +@end example + + The symbols used in the key sequences bound in the menu are fictitious +``function keys''; they don't appear on the keyboard, but that doesn't +stop you from using them in the menu. Their names were chosen to be +mnemonic, because they show up in the output of @code{where-is} and +@code{apropos} to identify the corresponding menu items. + + However, if you want the menu to be usable from the keyboard as well, +you must bind real @sc{ASCII} characters as well as fictitious function +keys. + +@node Menu Bar +@subsection The Menu Bar +@cindex menu bar + + Most window systems allow each frame to have a @dfn{menu bar}---a +permanently displayed menu stretching horizontally across the top of the +frame. The items of the menu bar are the subcommands of the fake +``function key'' @code{menu-bar}, as defined by all the active keymaps. + + To add an item to the menu bar, invent a fake ``function key'' of your +own (let's call it @var{key}), and make a binding for the key sequence +@code{[menu-bar @var{key}]}. Most often, the binding is a menu keymap, +so that pressing a button on the menu bar item leads to another menu. + + When more than one active keymap defines the same fake function key +for the menu bar, the item appears just once. If the user clicks on +that menu bar item, it brings up a single, combined submenu containing +all the subcommands of that item---the global subcommands, the local +subcommands, and the minor mode subcommands, all together. + + In order for a frame to display a menu bar, its @code{menu-bar-lines} +parameter must be greater than zero. Emacs uses just one line for the +menu bar itself; if you specify more than one line, the other lines +serve to separate the menu bar from the windows in the frame. We +recommend you try 1 or 2 as the value of @code{menu-bar-lines}. @xref{X +Frame Parameters}. + + Here's an example of setting up a menu bar item: + +@smallexample +(modify-frame-parameters (selected-frame) '((menu-bar-lines . 2))) + +;; @r{Make a menu keymap (with a prompt string)} +;; @r{and make it the menu bar item's definition.} +(define-key global-map [menu-bar words] + (cons "Words" (make-sparse-keymap "Words"))) + +@group +;; @r{Define specific subcommands in the item's menu.} +(define-key global-map + [menu-bar words forward] + '("Forward word" . forward-word)) +@end group +@group +(define-key global-map + [menu-bar words backward] + '("Backward word" . backward-word)) +@end group +@end smallexample + + A local keymap can cancel a menu bar item made by the global keymap by +rebinding the same fake function key with @code{undefined} as the +binding. For example, this is how Dired suppresses the @samp{Edit} menu +bar item: + +@example +(define-key dired-mode-map [menu-bar edit] 'undefined) +@end example + +@noindent +@code{edit} is the fake function key used by the global map for the +@samp{Edit} menu bar item. The main reason to suppress a global +menu bar item is to regain space for mode-specific items. + +@defvar menu-bar-final-items +Normally the menu bar shows global items followed by items defined by the +local maps. + +This variable holds a list of fake function keys for items to display at +the end of the menu bar rather than in normal sequence. The default +value is @code{(help)}; thus, the @samp{Help} menu item normally appears +at the end of the menu bar, following local menu items. +@end defvar + +@node Modifying Menus +@subsection Modifying Menus + + When you insert a new item in an existing menu, you probably want to +put it in a particular place among the menu's existing items. If you +use @code{define-key} to add the item, it normally goes at the front of +the menu. To put it elsewhere, use @code{define-key-after}: + +@defun define-key-after map key binding after +Define a binding in @var{map} for @var{key}, with value @var{binding}, +just like @code{define-key}, but position the binding in @var{map} after +the binding for the key @var{after}. For example, + +@example +(define-key-after my-menu [drink] + '("Drink" . drink-command) [eat]) +@end example + +@noindent +makes a binding for the fake function key @key{drink} and puts it +right after the binding for @key{eat}. +@end defun + +@node Active Keymaps +@section Active Keymaps +@cindex active keymap +@cindex global keymap +@cindex local keymap + + Emacs normally contains many keymaps; at any given time, just a few of +them are @dfn{active} in that they participate in the interpretation +of user input. These are the global keymap, the current buffer's +local keymap, and the keymaps of any enabled minor modes. + + The @dfn{global keymap} holds the bindings of keys that are defined +regardless of the current buffer, such as @kbd{C-f}. The variable +@code{global-map} holds this keymap, which is always active. + + Each buffer may have another keymap, its @dfn{local keymap}, which may +contain new or overriding definitions for keys. The current buffer's +local keymap is always active except when @code{overriding-local-map} +overrides it. Text properties can specify an alternative local map for +certain parts of the buffer; see @ref{Special Properties}. + + Each minor mode may have a keymap; if it does, the keymap is active +when the minor mode is enabled. + + The variable @code{overriding-local-map}, if non-@code{nil}, specifies +another local keymap that overrides the buffer's local map and all the +minor mode keymaps. + + All the active keymaps are used together to determine what command to +execute when a key is entered. Emacs searches these maps one by one, in +order of decreasing precedence, until it finds a binding in one of the maps. + + Normally, Emacs @emph{first} searches for the key in the minor mode +maps (one map at a time); if they do not supply a binding for the key, +Emacs searches the local map; if that too has no binding, Emacs then +searches the global map. However, if @code{overriding-local-map} is +non-@code{nil}, Emacs searches that map first, followed by the global +map. + + The procedure for searching a single keymap is called +@dfn{key lookup}; see @ref{Key Lookup}. + +@cindex major mode keymap + Since every buffer that uses the same major mode normally uses the +very same local keymap, it may appear as if the keymap is local to the +mode. A change to the local keymap of a buffer (using +@code{local-set-key}, for example) will be seen also in the other +buffers that share that keymap. + + The local keymaps that are used for Lisp mode, C mode, and several +other major modes exist even if they have not yet been used. These +local maps are the values of the variables @code{lisp-mode-map}, +@code{c-mode-map}, and so on. For most other modes, which are less +frequently used, the local keymap is constructed only when the mode is +used for the first time in a session. + + The minibuffer has local keymaps, too; they contain various completion +and exit commands. @xref{Intro to Minibuffers}. + + @xref{Standard Keymaps}, for a list of standard keymaps. + +@defvar global-map + This variable contains the default global keymap that maps Emacs +keyboard input to commands. The global keymap is normally this keymap. +The default global keymap is a full keymap that binds +@code{self-insert-command} to all of the printing characters. + +It is normal practice to change the bindings in the global map, but you +should not assign this variable any value other than the keymap it starts +out with. +@end defvar + +@defun current-global-map + This function returns the current global keymap. This is the +same as the value of @code{global-map} unless you change one or the +other. + +@example +@group +(current-global-map) +@result{} (keymap [set-mark-command beginning-of-line @dots{} + delete-backward-char]) +@end group +@end example +@end defun + +@defun current-local-map + This function returns the current buffer's local keymap, or @code{nil} +if it has none. In the following example, the keymap for the +@samp{*scratch*} buffer (using Lisp Interaction mode) is a sparse keymap +in which the entry for @key{ESC}, @sc{ASCII} code 27, is another sparse +keymap. + +@example +@group +(current-local-map) +@result{} (keymap + (10 . eval-print-last-sexp) + (9 . lisp-indent-line) + (127 . backward-delete-char-untabify) +@end group +@group + (27 keymap + (24 . eval-defun) + (17 . indent-sexp))) +@end group +@end example +@end defun + +@defun current-minor-mode-maps +This function returns a list of the keymaps of currently enabled minor modes. +@end defun + +@defun use-global-map keymap + This function makes @var{keymap} the new current global keymap. It +returns @code{nil}. + + It is very unusual to change the global keymap. +@end defun + +@defun use-local-map keymap + This function makes @var{keymap} the new local keymap of the current +buffer. If @var{keymap} is @code{nil}, then the buffer has no local +keymap. @code{use-local-map} returns @code{nil}. Most major mode +commands use this function. +@end defun + +@c Emacs 19 feature +@defvar minor-mode-map-alist +This variable is an alist describing keymaps that may or may not be +active according to the values of certain variables. Its elements look +like this: + +@example +(@var{variable} . @var{keymap}) +@end example + +The keymap @var{keymap} is active whenever @var{variable} has a +non-@code{nil} value. Typically @var{variable} is the variable which +enables or disables a minor mode. @xref{Keymaps and Minor Modes}. + +Note that elements of @code{minor-mode-map-alist} do not have the same +structure as elements of @code{minor-mode-alist}. The map must be the +@sc{cdr} of the element; a list with the map as the second element will +not do. + +What's more, the keymap itself must appear in the @sc{cdr}. It does not +work to store a variable in the @sc{cdr} and make the map the value of +that variable. + +When more than one minor mode keymap is active, their order of priority +is the order of @code{minor-mode-map-alist}. But you should design +minor modes so that they don't interfere with each other. If you do +this properly, the order will not matter. + +See also @code{minor-mode-key-binding} in @ref{Functions for Key +Lookup}. See @ref{Keymaps and Minor Modes}, for more information about +minor modes. +@end defvar + +@defvar overriding-local-map +If non-@code{nil}, a keymap to use instead of the buffer's local keymap +and instead of all the minor mode keymaps. This keymap, if any, +overrides all other maps that would have been active, except for the +current global map. +@end defvar + +@node Key Lookup +@section Key Lookup +@cindex key lookup +@cindex keymap entry + + @dfn{Key lookup} is the process of finding the binding of a key +sequence from a given keymap. Actual execution of the binding is not +part of key lookup. + + Key lookup uses just the event types of each event in the key +sequence; the rest of the event is ignored. In fact, a key sequence +used for key lookup may designate mouse events with just their types +(symbols) instead of with entire mouse events (lists). @xref{Input +Events}. Such a pseudo-key-sequence is insufficient for +@code{command-execute}, but it is sufficient for looking up or rebinding +a key. + + When the key sequence consists of multiple events, key lookup +processes the events sequentially: the binding of the first event is +found, and must be a keymap; then the second event's binding is found in +that keymap, and so on until all the events in the key sequence are used +up. (The binding thus found for the last event may or may not be a +keymap.) Thus, the process of key lookup is defined in terms of a +simpler process for looking up a single event in a keymap. How that is +done depends on the type of object associated with the event in that +keymap. + + Let's use the term @dfn{keymap entry} to describe the value found by +looking up an event type in a keymap. (This doesn't include the item +string and other extra elements in menu key bindings because +@code{lookup-key} and other key lookup functions don't include them in +the returned value.) While any Lisp object may be stored in a keymap as +a keymap entry, not all make sense for key lookup. Here is a list of +the meaningful kinds of keymap entries: + +@table @asis +@item @code{nil} +@cindex @code{nil} in keymap +@code{nil} means that the events used so far in the lookup form an +undefined key. When a keymap fails to mention an event type at all, and +has no default binding, that is equivalent to a binding of @code{nil} +for that event type. + +@item @var{keymap} +@cindex keymap in keymap +The events used so far in the lookup form a prefix key. The next +event of the key sequence is looked up in @var{keymap}. + +@item @var{command} +@cindex command in keymap +The events used so far in the lookup form a complete key, +and @var{command} is its binding. + +@item @var{string} +@itemx @var{vector} +@cindex string in keymap +The events used so far in the lookup form a complete key, whose +binding is a keyboard macro. See @ref{Keyboard Macros}, for more +information. + +@item @var{list} +@cindex list in keymap +The meaning of a list depends on the types of the elements of the list. + +@itemize @bullet +@item +If the @sc{car} of @var{list} is the symbol @code{keymap}, then the list +is a keymap, and is treated as a keymap (see above). + +@item +@cindex @code{lambda} in keymap +If the @sc{car} of @var{list} is @code{lambda}, then the list is a +lambda expression. This is presumed to be a command, and is treated as +such (see above). + +@item +If the @sc{car} of @var{list} is a keymap and the @sc{cdr} is an event +type, then this is an @dfn{indirect entry}: + +@example +(@var{othermap} . @var{othertype}) +@end example + +When key lookup encounters an indirect entry, it looks up instead the +binding of @var{othertype} in @var{othermap} and uses that. + +This feature permits you to define one key as an alias for another key. +For example, an entry whose @sc{car} is the keymap called @code{esc-map} +and whose @sc{cdr} is 32 (the code for space) means, ``Use the global +binding of @kbd{Meta-@key{SPC}}, whatever that may be.'' +@end itemize + +@item @var{symbol} +@cindex symbol in keymap +The function definition of @var{symbol} is used in place of +@var{symbol}. If that too is a symbol, then this process is repeated, +any number of times. Ultimately this should lead to an object which is +a keymap, a command or a keyboard macro. A list is allowed if it is a +keymap or a command, but indirect entries are not understood when found +via symbols. + +Note that keymaps and keyboard macros (strings and vectors) are not +valid functions, so a symbol with a keymap, string or vector as its +function definition is also invalid as a function. It is, however, +valid as a key binding. If the definition is a keyboard macro, then the +symbol is also valid as an argument to @code{command-execute} +(@pxref{Interactive Call}). + +@cindex @code{undefined} in keymap +The symbol @code{undefined} is worth special mention: it means to treat +the key as undefined. Strictly speaking, the key is defined, and its +binding is the command @code{undefined}; but that command does the same +thing that is done automatically for an undefined key: it rings the bell +(by calling @code{ding}) but does not signal an error. + +@cindex preventing prefix key +@code{undefined} is used in local keymaps to override a global key +binding and make the key ``undefined'' locally. A local binding of +@code{nil} would fail to do this because it would not override the +global binding. + +@item @var{anything else} +If any other type of object is found, the events used so far in the +lookup form a complete key, and the object is its binding, but the +binding is not executable as a command. +@end table + + In short, a keymap entry may be a keymap, a command, a keyboard macro, +a symbol which leads to one of them, or an indirection or @code{nil}. +Here is an example of a sparse keymap with two characters bound to +commands and one bound to another keymap. This map is the normal value +of @code{emacs-lisp-mode-map}. Note that 9 is the code for @key{TAB}, +127 for @key{DEL}, 27 for @key{ESC}, 17 for @kbd{C-q} and 24 for +@kbd{C-x}. + +@example +@group +(keymap (9 . lisp-indent-line) + (127 . backward-delete-char-untabify) + (27 keymap (17 . indent-sexp) (24 . eval-defun))) +@end group +@end example + +@node Functions for Key Lookup +@section Functions for Key Lookup + + Here are the functions and variables pertaining to key lookup. + +@defun lookup-key keymap key &optional accept-defaults +This function returns the definition of @var{key} in @var{keymap}. If +the string or vector @var{key} is not a valid key sequence according to +the prefix keys specified in @var{keymap} (which means it is ``too +long'' and has extra events at the end), then the value is a number, the +number of events at the front of @var{key} that compose a complete key. + +@c Emacs 19 feature +If @var{accept-defaults} is non-@code{nil}, then @code{lookup-key} +considers default bindings as well as bindings for the specific events +in @var{key}. Otherwise, @code{lookup-key} reports only bindings for +the specific sequence @var{key}, ignoring default bindings except when +an element of @var{key} is @code{t}. + +All the other functions described in this chapter that look up keys use +@code{lookup-key}. + +@example +@group +(lookup-key (current-global-map) "\C-x\C-f") + @result{} find-file +@end group +@group +(lookup-key (current-global-map) "\C-x\C-f12345") + @result{} 2 +@end group +@end example + + If @var{key} contains a meta character, that character is implicitly +replaced by a two-character sequence: the value of +@code{meta-prefix-char}, followed by the corresponding non-meta +character. Thus, the first example below is handled by conversion into +the second example. + +@example +@group +(lookup-key (current-global-map) "\M-f") + @result{} forward-word +@end group +@group +(lookup-key (current-global-map) "\ef") + @result{} forward-word +@end group +@end example + +Unlike @code{read-key-sequence}, this function does not modify the +specified events in ways that discard information (@pxref{Key Sequence +Input}). In particular, it does not convert letters to lower case and +it does not change drag events to clicks. +@end defun + +@deffn Command undefined +Used in keymaps to undefine keys. It calls @code{ding}, but does +not cause an error. +@end deffn + +@defun key-binding key &optional accept-defaults +This function returns the binding for @var{key} in the current +keymaps, trying all the active keymaps. The result is @code{nil} if +@var{key} is undefined in the keymaps. + +@c Emacs 19 feature +The argument @var{accept-defaults} controls checking for default +bindings, as in @code{lookup-key}. + +An error is signaled if @var{key} is not a string or a vector. + +@example +@group +(key-binding "\C-x\C-f") + @result{} find-file +@end group +@end example +@end defun + +@defun local-key-binding key &optional accept-defaults +This function returns the binding for @var{key} in the current +local keymap, or @code{nil} if it is undefined there. + +@c Emacs 19 feature +The argument @var{accept-defaults} controls checking for default bindings, +as in @code{lookup-key} (above). +@end defun + +@defun global-key-binding key &optional accept-defaults +This function returns the binding for command @var{key} in the +current global keymap, or @code{nil} if it is undefined there. + +@c Emacs 19 feature +The argument @var{accept-defaults} controls checking for default bindings, +as in @code{lookup-key} (above). +@end defun + +@c Emacs 19 feature +@defun minor-mode-key-binding key &optional accept-defaults +This function returns a list of all the active minor mode bindings of +@var{key}. More precisely, it returns an alist of pairs +@code{(@var{modename} . @var{binding})}, where @var{modename} is the the +variable which enables the minor mode, and @var{binding} is @var{key}'s +binding in that mode. If @var{key} has no minor-mode bindings, the +value is @code{nil}. + +If the first binding is not a prefix command, all subsequent bindings +from other minor modes are omitted, since they would be completely +shadowed. Similarly, the list omits non-prefix bindings that follow +prefix bindings. + +The argument @var{accept-defaults} controls checking for default +bindings, as in @code{lookup-key} (above). +@end defun + +@defvar meta-prefix-char +@cindex @key{ESC} +This variable is the meta-prefix character code. It is used when +translating a meta character to a two-character sequence so it can be +looked up in a keymap. For useful results, the value should be a prefix +event (@pxref{Prefix Keys}). The default value is 27, which is the +@sc{ASCII} code for @key{ESC}. + +As long as the value of @code{meta-prefix-char} remains 27, key +lookup translates @kbd{M-b} into @kbd{@key{ESC} b}, which is normally +defined as the @code{backward-word} command. However, if you set +@code{meta-prefix-char} to 24, the code for @kbd{C-x}, then Emacs will +translate @kbd{M-b} into @kbd{C-x b}, whose standard binding is the +@code{switch-to-buffer} command. + +@smallexample +@group +meta-prefix-char ; @r{The default value.} + @result{} 27 +@end group +@group +(key-binding "\M-b") + @result{} backward-word +@end group +@group +?\C-x ; @r{The print representation} + @result{} 24 ; @r{of a character.} +@end group +@group +(setq meta-prefix-char 24) + @result{} 24 +@end group +@group +(key-binding "\M-b") + @result{} switch-to-buffer ; @r{Now, typing @kbd{M-b} is} + ; @r{like typing @kbd{C-x b}.} + +(setq meta-prefix-char 27) ; @r{Avoid confusion!} + @result{} 27 ; @r{Restore the default value!} +@end group +@end smallexample +@end defvar + +@node Changing Key Bindings +@section Changing Key Bindings +@cindex changing key bindings +@cindex rebinding + + The way to rebind a key is to change its entry in a keymap. If you +change the global keymap, the change is effective in all buffers (except +those that override the global binding with a local one). If you change +the current buffer's local map, that usually affects all buffers using +the same major mode. The @code{global-set-key} and @code{local-set-key} +functions are convenient interfaces for these operations. Or you can +use @code{define-key} and specify explicitly which map to change. + + People often use @code{global-set-key} in their @file{.emacs} file for +simple customization. For example, + +@smallexample +(global-set-key "\C-x\C-\\" 'next-line) +@end smallexample + +@noindent +or + +@smallexample +(global-set-key [?\C-x ?\C-\\] 'next-line) +@end smallexample + +@noindent +redefines @kbd{C-x C-\} to move down a line. + +@smallexample +(global-set-key [M-mouse-1] 'mouse-set-point) +@end smallexample + +@noindent +redefines the first (leftmost) mouse button, typed with the Meta key, to +set point where you click. + +@cindex meta character key constants +@cindex control character key constants + In writing the key sequence to rebind, it is useful to use the special +escape sequences for control and meta characters (@pxref{String Type}). +The syntax @samp{\C-} means that the following character is a control +character and @samp{\M-} means that the following character is a meta +character. Thus, the string @code{"\M-x"} is read as containing a +single @kbd{M-x}, @code{"\C-f"} is read as containing a single +@kbd{C-f}, and @code{"\M-\C-x"} and @code{"\C-\M-x"} are both read as +containing a single @kbd{C-M-x}. + + For the functions below, an error is signaled if @var{keymap} is not a +keymap or if @var{key} is not a string or vector representing a key +sequence. You can use event types (symbols) as shorthand for events +that are lists. + +@defun define-key keymap key binding + This function sets the binding for @var{key} in @var{keymap}. (If +@var{key} is more than one event long, the change is actually made +in another keymap reached from @var{keymap}.) The argument +@var{binding} can be any Lisp object, but only certain types are +meaningful. (For a list of meaningful types, see @ref{Key Lookup}.) +The value returned by @code{define-key} is @var{binding}. + +@cindex invalid prefix key error +@cindex key sequence error + Every prefix of @var{key} must be a prefix key (i.e., bound to a +keymap) or undefined; otherwise an error is signaled. + +If some prefix of @var{key} is undefined, then @code{define-key} defines +it as a prefix key so that the rest of @var{key} may be defined as +specified. +@end defun + + This example creates a sparse keymap and makes a number of bindings: + +@smallexample +@group +(setq map (make-sparse-keymap)) + @result{} (keymap) +@end group +@group +(define-key map "\C-f" 'forward-char) + @result{} forward-char +@end group +@group +map + @result{} (keymap (6 . forward-char)) +@end group + +@group +;; @r{Build sparse submap for @kbd{C-x} and bind @kbd{f} in that.} +(define-key map "\C-xf" 'forward-word) + @result{} forward-word +@end group +@group +map +@result{} (keymap + (24 keymap ; @kbd{C-x} + (102 . forward-word)) ; @kbd{f} + (6 . forward-char)) ; @kbd{C-f} +@end group + +@group +;; @r{Bind @kbd{C-p} to the @code{ctl-x-map}.} +(define-key map "\C-p" ctl-x-map) +;; @code{ctl-x-map} +@result{} [nil @dots{} find-file @dots{} backward-kill-sentence] +@end group + +@group +;; @r{Bind @kbd{C-f} to @code{foo} in the @code{ctl-x-map}.} +(define-key map "\C-p\C-f" 'foo) +@result{} 'foo +@end group +@group +map +@result{} (keymap ; @r{Note @code{foo} in @code{ctl-x-map}.} + (16 keymap [nil @dots{} foo @dots{} backward-kill-sentence]) + (24 keymap + (102 . forward-word)) + (6 . forward-char)) +@end group +@end smallexample + +@noindent +Note that storing a new binding for @kbd{C-p C-f} actually works by +changing an entry in @code{ctl-x-map}, and this has the effect of +changing the bindings of both @kbd{C-p C-f} and @kbd{C-x C-f} in the +default global map. + +@defun substitute-key-definition olddef newdef keymap &optional oldmap +@cindex replace bindings +This function replaces @var{olddef} with @var{newdef} for any keys in +@var{keymap} that were bound to @var{olddef}. In other words, +@var{olddef} is replaced with @var{newdef} wherever it appears. The +function returns @code{nil}. + +For example, this redefines @kbd{C-x C-f}, if you do it in an Emacs with +standard bindings: + +@smallexample +@group +(substitute-key-definition + 'find-file 'find-file-read-only (current-global-map)) +@end group +@end smallexample + +@c Emacs 19 feature +If @var{oldmap} is non-@code{nil}, then its bindings determine which +keys to rebind. The rebindings still happen in @var{newmap}, not in +@var{oldmap}. Thus, you can change one map under the control of the +bindings in another. For example, + +@smallexample +(substitute-key-definition + 'delete-backward-char 'my-funny-delete + my-map global-map) +@end smallexample + +@noindent +puts the special deletion command in @code{my-map} for whichever keys +are globally bound to the standard deletion command. + +@ignore +@c Emacs 18 only +Prefix keymaps that appear within @var{keymap} are not checked +recursively for keys bound to @var{olddef}; they are not changed at all. +Perhaps it would be better to check nested keymaps recursively. +@end ignore + +Here is an example showing a keymap before and after substitution: + +@smallexample +@group +(setq map '(keymap + (?1 . olddef-1) + (?2 . olddef-2) + (?3 . olddef-1))) +@result{} (keymap (49 . olddef-1) (50 . olddef-2) (51 . olddef-1)) +@end group + +@group +(substitute-key-definition 'olddef-1 'newdef map) +@result{} nil +@end group +@group +map +@result{} (keymap (49 . newdef) (50 . olddef-2) (51 . newdef)) +@end group +@end smallexample +@end defun + +@defun suppress-keymap keymap &optional nodigits +@cindex @code{self-insert-command} override +This function changes the contents of the full keymap @var{keymap} by +making all the printing characters undefined. More precisely, it binds +them to the command @code{undefined}. This makes ordinary insertion of +text impossible. @code{suppress-keymap} returns @code{nil}. + +If @var{nodigits} is @code{nil}, then @code{suppress-keymap} defines +digits to run @code{digit-argument}, and @kbd{-} to run +@code{negative-argument}. Otherwise it makes them undefined like the +rest of the printing characters. + +@cindex yank suppression +@cindex @code{quoted-insert} suppression +The @code{suppress-keymap} function does not make it impossible to +modify a buffer, as it does not suppress commands such as @code{yank} +and @code{quoted-insert}. To prevent any modification of a buffer, make +it read-only (@pxref{Read Only Buffers}). + +Since this function modifies @var{keymap}, you would normally use it +on a newly created keymap. Operating on an existing keymap +that is used for some other purpose is likely to cause trouble; for +example, suppressing @code{global-map} would make it impossible to use +most of Emacs. + +Most often, @code{suppress-keymap} is used to initialize local +keymaps of modes such as Rmail and Dired where insertion of text is not +desirable and the buffer is read-only. Here is an example taken from +the file @file{emacs/lisp/dired.el}, showing how the local keymap for +Dired mode is set up: + +@smallexample +@group + @dots{} + (setq dired-mode-map (make-keymap)) + (suppress-keymap dired-mode-map) + (define-key dired-mode-map "r" 'dired-rename-file) + (define-key dired-mode-map "\C-d" 'dired-flag-file-deleted) + (define-key dired-mode-map "d" 'dired-flag-file-deleted) + (define-key dired-mode-map "v" 'dired-view-file) + (define-key dired-mode-map "e" 'dired-find-file) + (define-key dired-mode-map "f" 'dired-find-file) + @dots{} +@end group +@end smallexample +@end defun + +@node Key Binding Commands +@section Commands for Binding Keys + + This section describes some convenient interactive interfaces for +changing key bindings. They work by calling @code{define-key}. + +@deffn Command global-set-key key definition + This function sets the binding of @var{key} in the current global map +to @var{definition}. + +@smallexample +@group +(global-set-key @var{key} @var{definition}) +@equiv{} +(define-key (current-global-map) @var{key} @var{definition}) +@end group +@end smallexample +@end deffn + +@deffn Command global-unset-key key +@cindex unbinding keys + This function removes the binding of @var{key} from the current +global map. + +One use of this function is in preparation for defining a longer key +which uses it implicitly as a prefix---which would not be allowed if +@var{key} has a non-prefix binding. For example: + +@smallexample +@group +(global-unset-key "\C-l") + @result{} nil +@end group +@group +(global-set-key "\C-l\C-l" 'redraw-display) + @result{} nil +@end group +@end smallexample + +This function is implemented simply using @code{define-key}: + +@smallexample +@group +(global-unset-key @var{key}) +@equiv{} +(define-key (current-global-map) @var{key} nil) +@end group +@end smallexample +@end deffn + +@deffn Command local-set-key key definition + This function sets the binding of @var{key} in the current local +keymap to @var{definition}. + +@smallexample +@group +(local-set-key @var{key} @var{definition}) +@equiv{} +(define-key (current-local-map) @var{key} @var{definition}) +@end group +@end smallexample +@end deffn + +@deffn Command local-unset-key key + This function removes the binding of @var{key} from the current +local map. + +@smallexample +@group +(local-unset-key @var{key}) +@equiv{} +(define-key (current-local-map) @var{key} nil) +@end group +@end smallexample +@end deffn + +@node Scanning Keymaps +@section Scanning Keymaps + + This section describes functions used to scan all the current keymaps +for the sake of printing help information. + +@defun accessible-keymaps keymap &optional prefix +This function returns a list of all the keymaps that can be accessed +(via prefix keys) from @var{keymap}. The value is an association list +with elements of the form @code{(@var{key} .@: @var{map})}, where +@var{key} is a prefix key whose definition in @var{keymap} is +@var{map}. + +The elements of the alist are ordered so that the @var{key} increases +in length. The first element is always @code{("" .@: @var{keymap})}, +because the specified keymap is accessible from itself with a prefix of +no events. + +If @var{prefix} is given, it should be a prefix key sequence; then +@code{accessible-keymaps} includes only the submaps whose prefixes start +with @var{prefix}. These elements look just as they do in the value of +@code{(accessible-keymaps)}; the only difference is that some elements +are omitted. + +In the example below, the returned alist indicates that the key +@key{ESC}, which is displayed as @samp{^[}, is a prefix key whose +definition is the sparse keymap @code{(keymap (83 .@: center-paragraph) +(115 .@: foo))}. + +@smallexample +@group +(accessible-keymaps (current-local-map)) +@result{}(("" keymap + (27 keymap ; @r{Note this keymap for @key{ESC} is repeated below.} + (83 . center-paragraph) + (115 . center-line)) + (9 . tab-to-tab-stop)) +@end group + +@group + ("^[" keymap + (83 . center-paragraph) + (115 . foo))) +@end group +@end smallexample + +In the following example, @kbd{C-h} is a prefix key that uses a sparse +keymap starting with @code{(keymap (118 . describe-variable)@dots{})}. +Another prefix, @kbd{C-x 4}, uses a keymap which happens to be +@code{ctl-x-4-map}. The event @code{mode-line} is one of several dummy +events used as prefixes for mouse actions in special parts of a window. + +@smallexample +@group +(accessible-keymaps (current-global-map)) +@result{} (("" keymap [set-mark-command beginning-of-line @dots{} + delete-backward-char]) +@end group +@group + ("^H" keymap (118 . describe-variable) @dots{} + (8 . help-for-help)) +@end group +@group + ("^X" keymap [x-flush-mouse-queue @dots{} + backward-kill-sentence]) +@end group +@group + ("^[" keymap [mark-sexp backward-sexp @dots{} + backward-kill-word]) +@end group + ("^X4" keymap (15 . display-buffer) @dots{}) +@group + ([mode-line] keymap + (S-mouse-2 . mouse-split-window-horizontally) @dots{})) +@end group +@end smallexample + +@noindent +These are not all the keymaps you would see in an actual case. +@end defun + +@defun where-is-internal command &optional keymap firstonly noindirect +This function returns a list of key sequences (of any length) that are +bound to @var{command} in a set of keymaps. + +The argument @var{command} can be any object; it is compared with all +keymap entries using @code{eq}. + +If @var{keymap} is @code{nil}, then the maps used are the current active +keymaps, disregarding @code{overriding-local-map} (that is, pretending +its value is @code{nil}). If @var{keymap} is non-@code{nil}, then the +maps searched are @var{keymap} and the global keymap. + +Usually it's best to use @code{overriding-local-map} as the expression +for @var{keymap}. Then @code{where-is-internal} searches precisely the +keymaps that are active. To search only the global map, pass +@code{(keymap)} (an empty keymap) as @var{keymap}. + +If @var{firstonly} is @code{non-ascii}, then the value is a single +string representing the first key sequence found, rather than a list of +all possible key sequences. If @var{firstonly} is @code{t}, then the +value is the first key sequence, except that key sequences consisting +entirely of @sc{ASCII} characters (or meta variants of @sc{ASCII} +characters) are preferred to all other key sequences. + +If @var{noindirect} is non-@code{nil}, @code{where-is-internal} doesn't +follow indirections to other keymaps or slots. This makes it possible +to search for an indirect definition itself. + +This function is used by @code{where-is} (@pxref{Help, , Help, emacs, +The GNU Emacs Manual}). + +@smallexample +@group +(where-is-internal 'describe-function) + @result{} ("\^hf" "\^hd") +@end group +@end smallexample +@end defun + +@deffn Command describe-bindings prefix +This function creates a listing of all defined keys, and their +definitions. It writes the listing in a buffer named @samp{*Help*} and +displays it in a window. + +The listing describes meta characters as @key{ESC} followed by the +corresponding non-meta character. + +When several characters with consecutive @sc{ASCII} codes have the +same definition, they are shown together, as +@samp{@var{firstchar}..@var{lastchar}}. In this instance, you need to +know the @sc{ASCII} codes to understand which characters this means. +For example, in the default global map, the characters @samp{@key{SPC} +..@: ~} are described by a single line. @key{SPC} is @sc{ASCII} 32, +@kbd{~} is @sc{ASCII} 126, and the characters between them include all +the normal printing characters, (e.g., letters, digits, punctuation, +etc.@:); all these characters are bound to @code{self-insert-command}. + +If @var{prefix} is non-@code{nil}, it should be a prefix key; then the +listing includes only keys that start with @var{prefix}. +@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 @@ +@c -*-texinfo-*- +@c This is part of the GNU Emacs Lisp Reference Manual. +@c Copyright (C) 1990, 1991, 1992, 1993, 1994 Free Software Foundation, Inc. +@c See the file elisp.texi for copying conditions. +@setfilename ../info/lists +@node Lists, Sequences Arrays Vectors, Strings and Characters, Top +@chapter Lists +@cindex list +@cindex element (of list) + + A @dfn{list} represents a sequence of zero or more elements (which may +be any Lisp objects). The important difference between lists and +vectors is that two or more lists can share part of their structure; in +addition, you can insert or delete elements in a list without copying +the whole list. + +@menu +* Cons Cells:: How lists are made out of cons cells. +* Lists as Boxes:: Graphical notation to explain lists. +* List-related Predicates:: Is this object a list? Comparing two lists. +* List Elements:: Extracting the pieces of a list. +* Building Lists:: Creating list structure. +* Modifying Lists:: Storing new pieces into an existing list. +* Sets And Lists:: A list can represent a finite mathematical set. +* Association Lists:: A list can represent a finite relation or mapping. +@end menu + +@node Cons Cells +@section Lists and Cons Cells +@cindex lists and cons cells +@cindex @code{nil} and lists + + Lists in Lisp are not a primitive data type; they are built up from +@dfn{cons cells}. A cons cell is a data object which represents an ordered +pair. It records two Lisp objects, one labeled as the @sc{car}, and the +other labeled as the @sc{cdr}. These names are traditional; @sc{cdr} is +pronounced ``could-er.'' + + A list is a series of cons cells chained together, one cons cell per +element of the list. By convention, the @sc{car}s of the cons cells are +the elements of the list, and the @sc{cdr}s are used to chain the list: +the @sc{cdr} of each cons cell is the following cons cell. The @sc{cdr} +of the last cons cell is @code{nil}. This asymmetry between the +@sc{car} and the @sc{cdr} is entirely a matter of convention; at the +level of cons cells, the @sc{car} and @sc{cdr} slots have the same +characteristics. + + The symbol @code{nil} is considered a list as well as a symbol; it is +the list with no elements. For convenience, the symbol @code{nil} is +considered to have @code{nil} as its @sc{cdr} (and also as its +@sc{car}). + + The @sc{cdr} of any nonempty list @var{l} is a list containing all the +elements of @var{l} except the first. + +@node Lists as Boxes +@comment node-name, next, previous, up +@section Lists as Linked Pairs of Boxes +@cindex box representation for lists +@cindex lists represented as boxes +@cindex cons cell as box + + A cons cell can be illustrated as a pair of boxes. The first box +represents the @sc{car} and the second box represents the @sc{cdr}. +Here is an illustration of the two-element list, @code{(tulip lily)}, +made from two cons cells: + +@example +@group + --------------- --------------- +| car | cdr | | car | cdr | +| tulip | o---------->| lily | nil | +| | | | | | + --------------- --------------- +@end group +@end example + + Each pair of boxes represents a cons cell. Each box ``refers to'', +``points to'' or ``contains'' a Lisp object. (These terms are +synonymous.) The first box, which is the @sc{car} of the first cons +cell, contains the symbol @code{tulip}. The arrow from the @sc{cdr} of +the first cons cell to the second cons cell indicates that the @sc{cdr} +of the first cons cell points to the second cons cell. + + The same list can be illustrated in a different sort of box notation +like this: + +@example +@group + ___ ___ ___ ___ + |___|___|--> |___|___|--> nil + | | + | | + --> tulip --> lily +@end group +@end example + + Here is a more complex illustration, showing the three-element list, +@code{((pine needles) oak maple)}, the first element of which is a +two-element list: + +@example +@group + ___ ___ ___ ___ ___ ___ + |___|___|--> |___|___|--> |___|___|--> nil + | | | + | | | + | --> oak --> maple + | + | ___ ___ ___ ___ + --> |___|___|--> |___|___|--> nil + | | + | | + --> pine --> needles +@end group +@end example + + The same list represented in the first box notation looks like this: + +@example +@group + -------------- -------------- -------------- +| car | cdr | | car | cdr | | car | cdr | +| o | o------->| oak | o------->| maple | nil | +| | | | | | | | | | + -- | --------- -------------- -------------- + | + | + | -------------- ---------------- + | | car | cdr | | car | cdr | + ------>| pine | o------->| needles | nil | + | | | | | | + -------------- ---------------- +@end group +@end example + + @xref{List Type}, for the read and print syntax of lists, and for more +``box and arrow'' illustrations of lists. + +@node List-related Predicates +@section Predicates on Lists + + The following predicates test whether a Lisp object is an atom, is a +cons cell or is a list, or whether it is the distinguished object +@code{nil}. (Many of these predicates can be defined in terms of the +others, but they are used so often that it is worth having all of them.) + +@defun consp object +This function returns @code{t} if @var{object} is a cons cell, @code{nil} +otherwise. @code{nil} is not a cons cell, although it @emph{is} a list. +@end defun + +@defun atom object +@cindex atoms +This function returns @code{t} if @var{object} is an atom, @code{nil} +otherwise. All objects except cons cells are atoms. The symbol +@code{nil} is an atom and is also a list; it is the only Lisp object +which is both. + +@example +(atom @var{object}) @equiv{} (not (consp @var{object})) +@end example +@end defun + +@defun listp object +This function returns @code{t} if @var{object} is a cons cell or +@code{nil}. Otherwise, it returns @code{nil}. + +@example +@group +(listp '(1)) + @result{} t +@end group +@group +(listp '()) + @result{} t +@end group +@end example +@end defun + +@defun nlistp object +This function is the opposite of @code{listp}: it returns @code{t} if +@var{object} is not a list. Otherwise, it returns @code{nil}. + +@example +(listp @var{object}) @equiv{} (not (nlistp @var{object})) +@end example +@end defun + +@defun null object +This function returns @code{t} if @var{object} is @code{nil}, and +returns @code{nil} otherwise. This function is identical to @code{not}, +but as a matter of clarity we use @code{null} when @var{object} is +considered a list and @code{not} when it is considered a truth value +(see @code{not} in @ref{Combining Conditions}). + +@example +@group +(null '(1)) + @result{} nil +@end group +@group +(null '()) + @result{} t +@end group +@end example +@end defun + +@need 1000 + +@node List Elements +@section Accessing Elements of Lists +@cindex list elements + +@defun car cons-cell +This function returns the value pointed to by the first pointer of the +cons cell @var{cons-cell}. Expressed another way, this function +returns the @sc{car} of @var{cons-cell}. + +As a special case, if @var{cons-cell} is @code{nil}, then @code{car} +is defined to return @code{nil}; therefore, any list is a valid argument +for @code{car}. An error is signaled if the argument is not a cons cell +or @code{nil}. + +@example +@group +(car '(a b c)) + @result{} a +@end group +@group +(car '()) + @result{} nil +@end group +@end example +@end defun + +@defun cdr cons-cell +This function returns the value pointed to by the second pointer of +the cons cell @var{cons-cell}. Expressed another way, this function +returns the @sc{cdr} of @var{cons-cell}. + +As a special case, if @var{cons-cell} is @code{nil}, then @code{cdr} +is defined to return @code{nil}; therefore, any list is a valid argument +for @code{cdr}. An error is signaled if the argument is not a cons cell +or @code{nil}. + +@example +@group +(cdr '(a b c)) + @result{} (b c) +@end group +@group +(cdr '()) + @result{} nil +@end group +@end example +@end defun + +@defun car-safe object +This function lets you take the @sc{car} of a cons cell while avoiding +errors for other data types. It returns the @sc{car} of @var{object} if +@var{object} is a cons cell, @code{nil} otherwise. This is in contrast +to @code{car}, which signals an error if @var{object} is not a list. + +@example +@group +(car-safe @var{object}) +@equiv{} +(let ((x @var{object})) + (if (consp x) + (car x) + nil)) +@end group +@end example +@end defun + +@defun cdr-safe object +This function lets you take the @sc{cdr} of a cons cell while +avoiding errors for other data types. It returns the @sc{cdr} of +@var{object} if @var{object} is a cons cell, @code{nil} otherwise. +This is in contrast to @code{cdr}, which signals an error if +@var{object} is not a list. + +@example +@group +(cdr-safe @var{object}) +@equiv{} +(let ((x @var{object})) + (if (consp x) + (cdr x) + nil)) +@end group +@end example +@end defun + +@defun nth n list +This function returns the @var{n}th element of @var{list}. Elements +are numbered starting with zero, so the @sc{car} of @var{list} is +element number zero. If the length of @var{list} is @var{n} or less, +the value is @code{nil}. + +If @var{n} is negative, @code{nth} returns the first element of +@var{list}. + +@example +@group +(nth 2 '(1 2 3 4)) + @result{} 3 +@end group +@group +(nth 10 '(1 2 3 4)) + @result{} nil +@end group +@group +(nth -3 '(1 2 3 4)) + @result{} 1 + +(nth n x) @equiv{} (car (nthcdr n x)) +@end group +@end example +@end defun + +@defun nthcdr n list +This function returns the @var{n}th @sc{cdr} of @var{list}. In other +words, it removes the first @var{n} links of @var{list} and returns +what follows. + +If @var{n} is zero or negative, @code{nthcdr} returns all of +@var{list}. If the length of @var{list} is @var{n} or less, +@code{nthcdr} returns @code{nil}. + +@example +@group +(nthcdr 1 '(1 2 3 4)) + @result{} (2 3 4) +@end group +@group +(nthcdr 10 '(1 2 3 4)) + @result{} nil +@end group +@group +(nthcdr -3 '(1 2 3 4)) + @result{} (1 2 3 4) +@end group +@end example +@end defun + +@node Building Lists +@comment node-name, next, previous, up +@section Building Cons Cells and Lists +@cindex cons cells +@cindex building lists + + Many functions build lists, as lists reside at the very heart of Lisp. +@code{cons} is the fundamental list-building function; however, it is +interesting to note that @code{list} is used more times in the source +code for Emacs than @code{cons}. + +@defun cons object1 object2 +This function is the fundamental function used to build new list +structure. It creates a new cons cell, making @var{object1} the +@sc{car}, and @var{object2} the @sc{cdr}. It then returns the new cons +cell. The arguments @var{object1} and @var{object2} may be any Lisp +objects, but most often @var{object2} is a list. + +@example +@group +(cons 1 '(2)) + @result{} (1 2) +@end group +@group +(cons 1 '()) + @result{} (1) +@end group +@group +(cons 1 2) + @result{} (1 . 2) +@end group +@end example + +@cindex consing +@code{cons} is often used to add a single element to the front of a +list. This is called @dfn{consing the element onto the list}. For +example: + +@example +(setq list (cons newelt list)) +@end example + +Note that there is no conflict between the variable named @code{list} +used in this example and the function named @code{list} described below; +any symbol can serve both purposes. +@end defun + +@defun list &rest objects +This function creates a list with @var{objects} as its elements. The +resulting list is always @code{nil}-terminated. If no @var{objects} +are given, the empty list is returned. + +@example +@group +(list 1 2 3 4 5) + @result{} (1 2 3 4 5) +@end group +@group +(list 1 2 '(3 4 5) 'foo) + @result{} (1 2 (3 4 5) foo) +@end group +@group +(list) + @result{} nil +@end group +@end example +@end defun + +@defun make-list length object +This function creates a list of length @var{length}, in which all the +elements have the identical value @var{object}. Compare +@code{make-list} with @code{make-string} (@pxref{Creating Strings}). + +@example +@group +(make-list 3 'pigs) + @result{} (pigs pigs pigs) +@end group +@group +(make-list 0 'pigs) + @result{} nil +@end group +@end example +@end defun + +@defun append &rest sequences +@cindex copying lists +This function returns a list containing all the elements of +@var{sequences}. The @var{sequences} may be lists, vectors, or strings. +All arguments except the last one are copied, so none of them are +altered. + + The final argument to @code{append} may be any object but it is +typically a list. The final argument is not copied or converted; it +becomes part of the structure of the new list. + + Here is an example: + +@example +@group +(setq trees '(pine oak)) + @result{} (pine oak) +(setq more-trees (append '(maple birch) trees)) + @result{} (maple birch pine oak) +@end group + +@group +trees + @result{} (pine oak) +more-trees + @result{} (maple birch pine oak) +@end group +@group +(eq trees (cdr (cdr more-trees))) + @result{} t +@end group +@end example + +You can see what happens by looking at a box diagram. The variable +@code{trees} is set to the list @code{(pine oak)} and then the variable +@code{more-trees} is set to the list @code{(maple birch pine oak)}. +However, the variable @code{trees} continues to refer to the original +list: + +@smallexample +@group +more-trees trees +| | +| ___ ___ ___ ___ -> ___ ___ ___ ___ + --> |___|___|--> |___|___|--> |___|___|--> |___|___|--> nil + | | | | + | | | | + --> maple -->birch --> pine --> oak +@end group +@end smallexample + +An empty sequence contributes nothing to the value returned by +@code{append}. As a consequence of this, a final @code{nil} argument +forces a copy of the previous argument. + +@example +@group +trees + @result{} (pine oak) +@end group +@group +(setq wood (append trees ())) + @result{} (pine oak) +@end group +@group +wood + @result{} (pine oak) +@end group +@group +(eq wood trees) + @result{} nil +@end group +@end example + +@noindent +This once was the usual way to copy a list, before the function +@code{copy-sequence} was invented. @xref{Sequences Arrays Vectors}. + +With the help of @code{apply}, we can append all the lists in a list of +lists: + +@example +@group +(apply 'append '((a b c) nil (x y z) nil)) + @result{} (a b c x y z) +@end group +@end example + +If no @var{sequences} are given, @code{nil} is returned: + +@example +@group +(append) + @result{} nil +@end group +@end example + +See @code{nconc} in @ref{Rearrangement}, for a way to join lists with no +copying. + +Integers are also allowed as arguments to @code{append}. They are +converted to strings of digits making up the decimal print +representation of the integer, and these strings are then appended. +Here's what happens: + +@example +@group +(setq trees '(pine oak)) + @result{} (pine oak) +@end group +@group +(char-to-string 54) + @result{} "6" +@end group +@group +(setq longer-list (append trees 6 '(spruce))) + @result{} (pine oak 54 spruce) +@end group +@group +(setq x-list (append trees 6 6)) + @result{} (pine oak 54 . 6) +@end group +@end example + +This special case exists for compatibility with Mocklisp, and we don't +recommend you take advantage of it. If you want to convert an integer +in this way, use @code{format} (@pxref{Formatting Strings}) or +@code{number-to-string} (@pxref{String Conversion}). +@end defun + +@defun reverse list +This function creates a new list whose elements are the elements of +@var{list}, but in reverse order. The original argument @var{list} is +@emph{not} altered. + +@example +@group +(setq x '(1 2 3 4)) + @result{} (1 2 3 4) +@end group +@group +(reverse x) + @result{} (4 3 2 1) +x + @result{} (1 2 3 4) +@end group +@end example +@end defun + +@node Modifying Lists +@section Modifying Existing List Structure + + You can modify the @sc{car} and @sc{cdr} contents of a cons cell with the +primitives @code{setcar} and @code{setcdr}. + +@cindex CL note---@code{rplaca} vrs @code{setcar} +@quotation +@findex rplaca +@findex rplacd +@b{Common Lisp note:} Common Lisp uses functions @code{rplaca} and +@code{rplacd} to alter list structure; they change structure the same +way as @code{setcar} and @code{setcdr}, but the Common Lisp functions +return the cons cell while @code{setcar} and @code{setcdr} return the +new @sc{car} or @sc{cdr}. +@end quotation + +@menu +* Setcar:: Replacing an element in a list. +* Setcdr:: Replacing part of the list backbone. + This can be used to remove or add elements. +* Rearrangement:: Reordering the elements in a list; combining lists. +@end menu + +@node Setcar +@subsection Altering List Elements with @code{setcar} + + Changing the @sc{car} of a cons cell is done with @code{setcar}, which +replaces one element of a list with a different element. + +@defun setcar cons object +This function stores @var{object} as the new @sc{car} of @var{cons}, +replacing its previous @sc{car}. It returns the value @var{object}. +For example: + +@example +@group +(setq x '(1 2)) + @result{} (1 2) +@end group +@group +(setcar x 4) + @result{} 4 +@end group +@group +x + @result{} (4 2) +@end group +@end example +@end defun + + When a cons cell is part of the shared structure of several lists, +storing a new @sc{car} into the cons changes one element of each of +these lists. Here is an example: + +@example +@group +;; @r{Create two lists that are partly shared.} +(setq x1 '(a b c)) + @result{} (a b c) +(setq x2 (cons 'z (cdr x1))) + @result{} (z b c) +@end group + +@group +;; @r{Replace the @sc{car} of a shared link.} +(setcar (cdr x1) 'foo) + @result{} foo +x1 ; @r{Both lists are changed.} + @result{} (a foo c) +x2 + @result{} (z foo c) +@end group + +@group +;; @r{Replace the @sc{car} of a link that is not shared.} +(setcar x1 'baz) + @result{} baz +x1 ; @r{Only one list is changed.} + @result{} (baz foo c) +x2 + @result{} (z foo c) +@end group +@end example + + Here is a graphical depiction of the shared structure of the two lists +in the variables @code{x1} and @code{x2}, showing why replacing @code{b} +changes them both: + +@example +@group + ___ ___ ___ ___ ___ ___ +x1---> |___|___|----> |___|___|--> |___|___|--> nil + | --> | | + | | | | + --> a | --> b --> c + | + ___ ___ | +x2--> |___|___|-- + | + | + --> z +@end group +@end example + + Here is an alternative form of box diagram, showing the same relationship: + +@example +@group +x1: + -------------- -------------- -------------- +| car | cdr | | car | cdr | | car | cdr | +| a | o------->| b | o------->| c | nil | +| | | -->| | | | | | + -------------- | -------------- -------------- + | +x2: | + -------------- | +| car | cdr | | +| z | o---- +| | | + -------------- +@end group +@end example + +@node Setcdr +@subsection Altering the CDR of a List + + The lowest-level primitive for modifying a @sc{cdr} is @code{setcdr}: + +@defun setcdr cons object +This function stores @var{object} into the @sc{cdr} of @var{cons}. The +value returned is @var{object}, not @var{cons}. +@end defun + + Here is an example of replacing the @sc{cdr} of a list with a +different list. All but the first element of the list are removed in +favor of a different sequence of elements. The first element is +unchanged, because it resides in the @sc{car} of the list, and is not +reached via the @sc{cdr}. + +@example +@group +(setq x '(1 2 3)) + @result{} (1 2 3) +@end group +@group +(setcdr x '(4)) + @result{} (4) +@end group +@group +x + @result{} (1 4) +@end group +@end example + + You can delete elements from the middle of a list by altering the +@sc{cdr}s of the cons cells in the list. For example, here we delete +the second element, @code{b}, from the list @code{(a b c)}, by changing +the @sc{cdr} of the first cell: + +@example +@group +(setq x1 '(a b c)) + @result{} (a b c) +(setcdr x1 (cdr (cdr x1))) + @result{} (c) +x1 + @result{} (a c) +@end group +@end example + + Here is the result in box notation: + +@example +@group + -------------------- + | | + -------------- | -------------- | -------------- +| car | cdr | | | car | cdr | -->| car | cdr | +| a | o----- | b | o-------->| c | nil | +| | | | | | | | | + -------------- -------------- -------------- +@end group +@end example + +@noindent +The second cons cell, which previously held the element @code{b}, still +exists and its @sc{car} is still @code{b}, but it no longer forms part +of this list. + + It is equally easy to insert a new element by changing @sc{cdr}s: + +@example +@group +(setq x1 '(a b c)) + @result{} (a b c) +(setcdr x1 (cons 'd (cdr x1))) + @result{} (d b c) +x1 + @result{} (a d b c) +@end group +@end example + + Here is this result in box notation: + +@smallexample +@group + -------------- ------------- ------------- +| car | cdr | | car | cdr | | car | cdr | +| a | o | -->| b | o------->| c | nil | +| | | | | | | | | | | + --------- | -- | ------------- ------------- + | | + ----- -------- + | | + | --------------- | + | | car | cdr | | + -->| d | o------ + | | | + --------------- +@end group +@end smallexample + +@node Rearrangement +@subsection Functions that Rearrange Lists +@cindex rearrangement of lists +@cindex modification of lists + + Here are some functions that rearrange lists ``destructively'' by +modifying the @sc{cdr}s of their component cons cells. We call these +functions ``destructive'' because they chew up the original lists passed +to them as arguments, to produce a new list that is the returned value. + +@defun nconc &rest lists +@cindex concatenating lists +@cindex joining lists +This function returns a list containing all the elements of @var{lists}. +Unlike @code{append} (@pxref{Building Lists}), the @var{lists} are +@emph{not} copied. Instead, the last @sc{cdr} of each of the +@var{lists} is changed to refer to the following list. The last of the +@var{lists} is not altered. For example: + +@example +@group +(setq x '(1 2 3)) + @result{} (1 2 3) +@end group +@group +(nconc x '(4 5)) + @result{} (1 2 3 4 5) +@end group +@group +x + @result{} (1 2 3 4 5) +@end group +@end example + + Since the last argument of @code{nconc} is not itself modified, it is +reasonable to use a constant list, such as @code{'(4 5)}, as in the +above example. For the same reason, the last argument need not be a +list: + +@example +@group +(setq x '(1 2 3)) + @result{} (1 2 3) +@end group +@group +(nconc x 'z) + @result{} (1 2 3 . z) +@end group +@group +x + @result{} (1 2 3 . z) +@end group +@end example + +A common pitfall is to use a quoted constant list as a non-last +argument to @code{nconc}. If you do this, your program will change +each time you run it! Here is what happens: + +@smallexample +@group +(defun add-foo (x) ; @r{We want this function to add} + (nconc '(foo) x)) ; @r{@code{foo} to the front of its arg.} +@end group + +@group +(symbol-function 'add-foo) + @result{} (lambda (x) (nconc (quote (foo)) x)) +@end group + +@group +(setq xx (add-foo '(1 2))) ; @r{It seems to work.} + @result{} (foo 1 2) +@end group +@group +(setq xy (add-foo '(3 4))) ; @r{What happened?} + @result{} (foo 1 2 3 4) +@end group +@group +(eq xx xy) + @result{} t +@end group + +@group +(symbol-function 'add-foo) + @result{} (lambda (x) (nconc (quote (foo 1 2 3 4) x))) +@end group +@end smallexample +@end defun + +@defun nreverse list +@cindex reversing a list + This function reverses the order of the elements of @var{list}. +Unlike @code{reverse}, @code{nreverse} alters its argument destructively +by reversing the @sc{cdr}s in the cons cells forming the list. The cons +cell which used to be the last one in @var{list} becomes the first cell +of the value. + + For example: + +@example +@group +(setq x '(1 2 3 4)) + @result{} (1 2 3 4) +@end group +@group +x + @result{} (1 2 3 4) +(nreverse x) + @result{} (4 3 2 1) +@end group +@group +;; @r{The cell that was first is now last.} +x + @result{} (1) +@end group +@end example + + To avoid confusion, we usually store the result of @code{nreverse} +back in the same variable which held the original list: + +@example +(setq x (nreverse x)) +@end example + + Here is the @code{nreverse} of our favorite example, @code{(a b c)}, +presented graphically: + +@smallexample +@group +@r{Original list head:} @r{Reversed list:} + ------------- ------------- ------------ +| car | cdr | | car | cdr | | car | cdr | +| a | nil |<-- | b | o |<-- | c | o | +| | | | | | | | | | | | | + ------------- | --------- | - | -------- | - + | | | | + ------------- ------------ +@end group +@end smallexample +@end defun + +@defun sort list predicate +@cindex stable sort +@cindex sorting lists +This function sorts @var{list} stably, though destructively, and +returns the sorted list. It compares elements using @var{predicate}. A +stable sort is one in which elements with equal sort keys maintain their +relative order before and after the sort. Stability is important when +successive sorts are used to order elements according to different +criteria. + +The argument @var{predicate} must be a function that accepts two +arguments. It is called with two elements of @var{list}. To get an +increasing order sort, the @var{predicate} should return @code{t} if the +first element is ``less than'' the second, or @code{nil} if not. + +The destructive aspect of @code{sort} is that it rearranges the cons +cells forming @var{list} by changing @sc{cdr}s. A nondestructive sort +function would create new cons cells to store the elements in their +sorted order. If you wish to make a sorted copy without destroying the +original, copy it first with @code{copy-sequence} and then sort. + +Sorting does not change the @sc{car}s of the cons cells in @var{list}; +the cons cell that originally contained the element @code{a} in +@var{list} still has @code{a} in its @sc{car} after sorting, but it now +appears in a different position in the list due to the change of +@sc{cdr}s. For example: + +@example +@group +(setq nums '(1 3 2 6 5 4 0)) + @result{} (1 3 2 6 5 4 0) +@end group +@group +(sort nums '<) + @result{} (0 1 2 3 4 5 6) +@end group +@group +nums + @result{} (1 2 3 4 5 6) +@end group +@end example + +@noindent +Note that the list in @code{nums} no longer contains 0; this is the same +cons cell that it was before, but it is no longer the first one in the +list. Don't assume a variable that formerly held the argument now holds +the entire sorted list! Instead, save the result of @code{sort} and use +that. Most often we store the result back into the variable that held +the original list: + +@example +(setq nums (sort nums '<)) +@end example + +@xref{Sorting}, for more functions that perform sorting. +See @code{documentation} in @ref{Accessing Documentation}, for a +useful example of @code{sort}. +@end defun + +@ifinfo + See @code{delq}, in @ref{Sets And Lists}, for another function +that modifies cons cells. +@end ifinfo +@iftex + The function @code{delq} in the following section is another example +of destructive list manipulation. +@end iftex + +@node Sets And Lists +@section Using Lists as Sets +@cindex lists as sets +@cindex sets + + A list can represent an unordered mathematical set---simply consider a +value an element of a set if it appears in the list, and ignore the +order of the list. To form the union of two sets, use @code{append} (as +long as you don't mind having duplicate elements). Other useful +functions for sets include @code{memq} and @code{delq}, and their +@code{equal} versions, @code{member} and @code{delete}. + +@cindex CL note---lack @code{union}, @code{set} +@quotation +@b{Common Lisp note:} Common Lisp has functions @code{union} (which +avoids duplicate elements) and @code{intersection} for set operations, +but GNU Emacs Lisp does not have them. You can write them in Lisp if +you wish. +@end quotation + +@defun memq object list +@cindex membership in a list +This function tests to see whether @var{object} is a member of +@var{list}. If it is, @code{memq} returns a list starting with the +first occurrence of @var{object}. Otherwise, it returns @code{nil}. +The letter @samp{q} in @code{memq} says that it uses @code{eq} to +compare @var{object} against the elements of the list. For example: + +@example +@group +(memq 2 '(1 2 3 2 1)) + @result{} (2 3 2 1) +@end group +@group +(memq '(2) '((1) (2))) ; @r{@code{(2)} and @code{(2)} are not @code{eq}.} + @result{} nil +@end group +@end example +@end defun + +@defun delq object list +@cindex deletion of elements +This function destructively removes all elements @code{eq} to +@var{object} from @var{list}. The letter @samp{q} in @code{delq} says +that it uses @code{eq} to compare @var{object} against the elements of +the list, like @code{memq}. +@end defun + +When @code{delq} deletes elements from the front of the list, it does so +simply by advancing down the list and returning a sublist that starts +after those elements: + +@example +@group +(delq 'a '(a b c)) @equiv{} (cdr '(a b c)) +@end group +@end example + +When an element to be deleted appears in the middle of the list, +removing it involves changing the @sc{cdr}s (@pxref{Setcdr}). + +@example +@group +(setq sample-list '(1 2 3 (4))) + @result{} (1 2 3 (4)) +@end group +@group +(delq 1 sample-list) + @result{} (2 3 (4)) +@end group +@group +sample-list + @result{} (1 2 3 (4)) +@end group +@group +(delq 2 sample-list) + @result{} (1 3 (4)) +@end group +@group +sample-list + @result{} (1 3 (4)) +@end group +@end example + +Note that @code{(delq 2 sample-list)} modifies @code{sample-list} to +splice out the second element, but @code{(delq 1 sample-list)} does not +splice anything---it just returns a shorter list. Don't assume that a +variable which formerly held the argument @var{list} now has fewer +elements, or that it still holds the original list! Instead, save the +result of @code{delq} and use that. Most often we store the result back +into the variable that held the original list: + +@example +(setq flowers (delq 'rose flowers)) +@end example + +In the following example, the @code{(4)} that @code{delq} attempts to match +and the @code{(4)} in the @code{sample-list} are not @code{eq}: + +@example +@group +(delq '(4) sample-list) + @result{} (1 3 (4)) +@end group +@end example + +The following two functions are like @code{memq} and @code{delq} but use +@code{equal} rather than @code{eq} to compare elements. They are new in +Emacs 19. + +@defun member object list +The function @code{member} tests to see whether @var{object} is a member +of @var{list}, comparing members with @var{object} using @code{equal}. +If @var{object} is a member, @code{member} returns a list starting with +its first occurrence in @var{list}. Otherwise, it returns @code{nil}. + +Compare this with @code{memq}: + +@example +@group +(member '(2) '((1) (2))) ; @r{@code{(2)} and @code{(2)} are @code{equal}.} + @result{} ((2)) +@end group +@group +(memq '(2) '((1) (2))) ; @r{@code{(2)} and @code{(2)} are not @code{eq}.} + @result{} nil +@end group +@group +;; @r{Two strings with the same contents are @code{equal}.} +(member "foo" '("foo" "bar")) + @result{} ("foo" "bar") +@end group +@end example +@end defun + +@defun delete object list +This function destructively removes all elements @code{equal} to +@var{object} from @var{list}. It is to @code{delq} as @code{member} is +to @code{memq}: it uses @code{equal} to compare elements with +@var{object}, like @code{member}; when it finds an element that matches, +it removes the element just as @code{delq} would. For example: + +@example +@group +(delete '(2) '((2) (1) (2))) + @result{} '((1)) +@end group +@end example +@end defun + +@quotation +@b{Common Lisp note:} The functions @code{member} and @code{delete} in +GNU Emacs Lisp are derived from Maclisp, not Common Lisp. The Common +Lisp versions do not use @code{equal} to compare elements. +@end quotation + +@node Association Lists +@section Association Lists +@cindex association list +@cindex alist + + An @dfn{association list}, or @dfn{alist} for short, records a mapping +from keys to values. It is a list of cons cells called +@dfn{associations}: the @sc{car} of each cell is the @dfn{key}, and the +@sc{cdr} is the @dfn{associated value}.@footnote{This usage of ``key'' +is not related to the term ``key sequence''; it means a value used to +look up an item in a table. In this case, the table is the alist, and +the alist associations are the items.} + + Here is an example of an alist. The key @code{pine} is associated with +the value @code{cones}; the key @code{oak} is associated with +@code{acorns}; and the key @code{maple} is associated with @code{seeds}. + +@example +@group +'((pine . cones) + (oak . acorns) + (maple . seeds)) +@end group +@end example + + The associated values in an alist may be any Lisp objects; so may the +keys. For example, in the following alist, the symbol @code{a} is +associated with the number @code{1}, and the string @code{"b"} is +associated with the @emph{list} @code{(2 3)}, which is the @sc{cdr} of +the alist element: + +@example +((a . 1) ("b" 2 3)) +@end example + + Sometimes it is better to design an alist to store the associated +value in the @sc{car} of the @sc{cdr} of the element. Here is an +example: + +@example +'((rose red) (lily white) (buttercup yellow)) +@end example + +@noindent +Here we regard @code{red} as the value associated with @code{rose}. One +advantage of this method is that you can store other related +information---even a list of other items---in the @sc{cdr} of the +@sc{cdr}. One disadvantage is that you cannot use @code{rassq} (see +below) to find the element containing a given value. When neither of +these considerations is important, the choice is a matter of taste, as +long as you are consistent about it for any given alist. + + Note that the same alist shown above could be regarded as having the +associated value in the @sc{cdr} of the element; the value associated +with @code{rose} would be the list @code{(red)}. + + Association lists are often used to record information that you might +otherwise keep on a stack, since new associations may be added easily to +the front of the list. When searching an association list for an +association with a given key, the first one found is returned, if there +is more than one. + + In Emacs Lisp, it is @emph{not} an error if an element of an +association list is not a cons cell. The alist search functions simply +ignore such elements. Many other versions of Lisp signal errors in such +cases. + + Note that property lists are similar to association lists in several +respects. A property list behaves like an association list in which +each key can occur only once. @xref{Property Lists}, for a comparison +of property lists and association lists. + +@defun assoc key alist +This function returns the first association for @var{key} in +@var{alist}. It compares @var{key} against the alist elements using +@code{equal} (@pxref{Equality Predicates}). It returns @code{nil} if no +association in @var{alist} has a @sc{car} @code{equal} to @var{key}. +For example: + +@smallexample +(setq trees '((pine . cones) (oak . acorns) (maple . seeds))) + @result{} ((pine . cones) (oak . acorns) (maple . seeds)) +(assoc 'oak trees) + @result{} (oak . acorns) +(cdr (assoc 'oak trees)) + @result{} acorns +(assoc 'birch trees) + @result{} nil +@end smallexample + +Here is another example in which the keys and values are not symbols: + +@smallexample +(setq needles-per-cluster + '((2 "Austrian Pine" "Red Pine") + (3 "Pitch Pine") + (5 "White Pine"))) + +(cdr (assoc 3 needles-per-cluster)) + @result{} ("Pitch Pine") +(cdr (assoc 2 needles-per-cluster)) + @result{} ("Austrian Pine" "Red Pine") +@end smallexample +@end defun + +@defun assq key alist +This function is like @code{assoc} in that it returns the first +association for @var{key} in @var{alist}, but it makes the comparison +using @code{eq} instead of @code{equal}. @code{assq} returns @code{nil} +if no association in @var{alist} has a @sc{car} @code{eq} to @var{key}. +This function is used more often than @code{assoc}, since @code{eq} is +faster than @code{equal} and most alists use symbols as keys. +@xref{Equality Predicates}. + +@smallexample +(setq trees '((pine . cones) (oak . acorns) (maple . seeds))) + @result{} ((pine . cones) (oak . acorns) (maple . seeds)) +(assq 'pine trees) + @result{} (pine . cones) +@end smallexample + +On the other hand, @code{assq} is not usually useful in alists where the +keys may not be symbols: + +@smallexample +(setq leaves + '(("simple leaves" . oak) + ("compound leaves" . horsechestnut))) + +(assq "simple leaves" leaves) + @result{} nil +(assoc "simple leaves" leaves) + @result{} ("simple leaves" . oak) +@end smallexample +@end defun + +@defun rassq value alist +This function returns the first association with value @var{value} in +@var{alist}. It returns @code{nil} if no association in @var{alist} has +a @sc{cdr} @code{eq} to @var{value}. + +@code{rassq} is like @code{assq} except that it compares the @sc{cdr} of +each @var{alist} association instead of the @sc{car}. You can think of +this as ``reverse @code{assq}'', finding the key for a given value. + +For example: + +@smallexample +(setq trees '((pine . cones) (oak . acorns) (maple . seeds))) + +(rassq 'acorns trees) + @result{} (oak . acorns) +(rassq 'spores trees) + @result{} nil +@end smallexample + +Note that @code{rassq} cannot search for a value stored in the @sc{car} +of the @sc{cdr} of an element: + +@smallexample +(setq colors '((rose red) (lily white) (buttercup yellow))) + +(rassq 'white colors) + @result{} nil +@end smallexample + +In this case, the @sc{cdr} of the association @code{(lily white)} is not +the symbol @code{white}, but rather the list @code{(white)}. This +becomes clearer if the association is written in dotted pair notation: + +@smallexample +(lily white) @equiv{} (lily . (white)) +@end smallexample +@end defun + +@defun copy-alist alist +@cindex copying alists +This function returns a two-level deep copy of @var{alist}: it creates a +new copy of each association, so that you can alter the associations of +the new alist without changing the old one. + +@smallexample +@group +(setq needles-per-cluster + '((2 . ("Austrian Pine" "Red Pine")) + (3 . "Pitch Pine") + (5 . "White Pine"))) +@result{} +((2 "Austrian Pine" "Red Pine") + (3 . "Pitch Pine") + (5 . "White Pine")) + +(setq copy (copy-alist needles-per-cluster)) +@result{} +((2 "Austrian Pine" "Red Pine") + (3 . "Pitch Pine") + (5 . "White Pine")) + +(eq needles-per-cluster copy) + @result{} nil +(equal needles-per-cluster copy) + @result{} t +(eq (car needles-per-cluster) (car copy)) + @result{} nil +(cdr (car (cdr needles-per-cluster))) + @result{} "Pitch Pine" +(eq (cdr (car (cdr needles-per-cluster))) + (cdr (car (cdr copy)))) + @result{} t +@end group +@end smallexample +@end defun + + 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 @@ +@c -*-texinfo-*- +@c This is part of the GNU Emacs Lisp Reference Manual. +@c Copyright (C) 1990, 1991, 1992, 1993, 1994 Free Software Foundation, Inc. +@c See the file elisp.texi for copying conditions. +@setfilename ../info/macros +@node Macros, Loading, Functions, Top +@chapter Macros +@cindex macros + + @dfn{Macros} enable you to define new control constructs and other +language features. A macro is defined much like a function, but instead +of telling how to compute a value, it tells how to compute another Lisp +expression which will in turn compute the value. We call this +expression the @dfn{expansion} of the macro. + + Macros can do this because they operate on the unevaluated expressions +for the arguments, not on the argument values as functions do. They can +therefore construct an expansion containing these argument expressions +or parts of them. + + If you are using a macro to do something an ordinary function could +do, just for the sake of speed, consider using an inline function +instead. @xref{Inline Functions}. + +@menu +* Simple Macro:: A basic example. +* Expansion:: How, when and why macros are expanded. +* Compiling Macros:: How macros are expanded by the compiler. +* Defining Macros:: How to write a macro definition. +* Backquote:: Easier construction of list structure. +* Problems with Macros:: Don't evaluate the macro arguments too many times. + Don't hide the user's variables. +@end menu + +@node Simple Macro +@section A Simple Example of a Macro + + Suppose we would like to define a Lisp construct to increment a +variable value, much like the @code{++} operator in C. We would like to +write @code{(inc x)} and have the effect of @code{(setq x (1+ x))}. +Here's a macro definition that does the job: + +@findex inc +@example +@group +(defmacro inc (var) + (list 'setq var (list '1+ var))) +@end group +@end example + + When this is called with @code{(inc x)}, the argument @code{var} has +the value @code{x}---@emph{not} the @emph{value} of @code{x}. The body +of the macro uses this to construct the expansion, which is @code{(setq +x (1+ x))}. Once the macro definition returns this expansion, Lisp +proceeds to evaluate it, thus incrementing @code{x}. + +@node Expansion +@section Expansion of a Macro Call +@cindex expansion of macros +@cindex macro call + + A macro call looks just like a function call in that it is a list which +starts with the name of the macro. The rest of the elements of the list +are the arguments of the macro. + + Evaluation of the macro call begins like evaluation of a function call +except for one crucial difference: the macro arguments are the actual +expressions appearing in the macro call. They are not evaluated before +they are given to the macro definition. By contrast, the arguments of a +function are results of evaluating the elements of the function call +list. + + Having obtained the arguments, Lisp invokes the macro definition just +as a function is invoked. The argument variables of the macro are bound +to the argument values from the macro call, or to a list of them in the +case of a @code{&rest} argument. And the macro body executes and +returns its value just as a function body does. + + The second crucial difference between macros and functions is that the +value returned by the macro body is not the value of the macro call. +Instead, it is an alternate expression for computing that value, also +known as the @dfn{expansion} of the macro. The Lisp interpreter +proceeds to evaluate the expansion as soon as it comes back from the +macro. + + Since the expansion is evaluated in the normal manner, it may contain +calls to other macros. It may even be a call to the same macro, though +this is unusual. + + You can see the expansion of a given macro call by calling +@code{macroexpand}. + +@defun macroexpand form &optional environment +@cindex macro expansion +This function expands @var{form}, if it is a macro call. If the result +is another macro call, it is expanded in turn, until something which is +not a macro call results. That is the value returned by +@code{macroexpand}. If @var{form} is not a macro call to begin with, it +is returned as given. + +Note that @code{macroexpand} does not look at the subexpressions of +@var{form} (although some macro definitions may do so). Even if they +are macro calls themselves, @code{macroexpand} does not expand them. + +The function @code{macroexpand} does not expand calls to inline functions. +Normally there is no need for that, since a call to an inline function is +no harder to understand than a call to an ordinary function. + +If @var{environment} is provided, it specifies an alist of macro +definitions that shadow the currently defined macros. Byte compilation +uses this feature. + +@smallexample +@group +(defmacro inc (var) + (list 'setq var (list '1+ var))) + @result{} inc +@end group + +@group +(macroexpand '(inc r)) + @result{} (setq r (1+ r)) +@end group + +@group +(defmacro inc2 (var1 var2) + (list 'progn (list 'inc var1) (list 'inc var2))) + @result{} inc2 +@end group + +@group +(macroexpand '(inc2 r s)) + @result{} (progn (inc r) (inc s)) ; @r{@code{inc} not expanded here.} +@end group +@end smallexample +@end defun + +@node Compiling Macros +@section Macros and Byte Compilation +@cindex byte-compiling macros + + You might ask why we take the trouble to compute an expansion for a +macro and then evaluate the expansion. Why not have the macro body +produce the desired results directly? The reason has to do with +compilation. + + When a macro call appears in a Lisp program being compiled, the Lisp +compiler calls the macro definition just as the interpreter would, and +receives an expansion. But instead of evaluating this expansion, it +compiles the expansion as if it had appeared directly in the program. +As a result, the compiled code produces the value and side effects +intended for the macro, but executes at full compiled speed. This would +not work if the macro body computed the value and side effects +itself---they would be computed at compile time, which is not useful. + + In order for compilation of macro calls to work, the macros must be +defined in Lisp when the calls to them are compiled. The compiler has a +special feature to help you do this: if a file being compiled contains a +@code{defmacro} form, the macro is defined temporarily for the rest of +the compilation of that file. To use this feature, you must define the +macro in the same file where it is used and before its first use. + + Byte-compiling a file executes any @code{require} calls at top-level +in the file. This is in case the file needs the required packages for +proper compilation. One way to ensure that necessary macro definitions +are available during compilation is to require the file that defines +them. @xref{Features}. + +@node Defining Macros +@section Defining Macros + + A Lisp macro is a list whose @sc{car} is @code{macro}. Its @sc{cdr} should +be a function; expansion of the macro works by applying the function +(with @code{apply}) to the list of unevaluated argument-expressions +from the macro call. + + It is possible to use an anonymous Lisp macro just like an anonymous +function, but this is never done, because it does not make sense to pass +an anonymous macro to mapping functions such as @code{mapcar}. In +practice, all Lisp macros have names, and they are usually defined with +the special form @code{defmacro}. + +@defspec defmacro name argument-list body-forms@dots{} +@code{defmacro} defines the symbol @var{name} as a macro that looks +like this: + +@example +(macro lambda @var{argument-list} . @var{body-forms}) +@end example + +This macro object is stored in the function cell of @var{name}. The +value returned by evaluating the @code{defmacro} form is @var{name}, but +usually we ignore this value. + +The shape and meaning of @var{argument-list} is the same as in a +function, and the keywords @code{&rest} and @code{&optional} may be used +(@pxref{Argument List}). Macros may have a documentation string, but +any @code{interactive} declaration is ignored since macros cannot be +called interactively. +@end defspec + +@node Backquote +@section Backquote +@cindex backquote (list substitution) +@cindex ` (list substitution) + + Macros often need to construct large list structures from a mixture of +constants and nonconstant parts. To make this easier, use the macro +@code{`} (often called @dfn{backquote}). + + Backquote allows you to quote a list, but selectively evaluate +elements of that list. In the simplest case, it is identical to the +special form @code{quote} (@pxref{Quoting}). For example, these +two forms yield identical results: + +@example +@group +(` (a list of (+ 2 3) elements)) + @result{} (a list of (+ 2 3) elements) +@end group +@group +(quote (a list of (+ 2 3) elements)) + @result{} (a list of (+ 2 3) elements) +@end group +@end example + +@findex , @{(with Backquote)} +The special marker, @code{,}, inside of the argument to backquote, +indicates a value that isn't constant. Backquote evaluates the +argument of @code{,} and puts the value in the list structure: + +@example +@group +(list 'a 'list 'of (+ 2 3) 'elements) + @result{} (a list of 5 elements) +@end group +@group +(` (a list of (, (+ 2 3)) elements)) + @result{} (a list of 5 elements) +@end group +@end example + +@findex ,@@ @{(with Backquote)} +@cindex splicing (with backquote) +You can also @dfn{splice} an evaluated value into the resulting list, +using the special marker @code{,@@}. The elements of the spliced list +become elements at the same level as the other elements of the resulting +list. The equivalent code without using @code{`} is often unreadable. +Here are some examples: + +@example +@group +(setq some-list '(2 3)) + @result{} (2 3) +@end group +@group +(cons 1 (append some-list '(4) some-list)) + @result{} (1 2 3 4 2 3) +@end group +@group +(` (1 (,@@ some-list) 4 (,@@ some-list))) + @result{} (1 2 3 4 2 3) +@end group + +@group +(setq list '(hack foo bar)) + @result{} (hack foo bar) +@end group +@group +(cons 'use + (cons 'the + (cons 'words (append (cdr list) '(as elements))))) + @result{} (use the words foo bar as elements) +@end group +@group +(` (use the words (,@@ (cdr list)) as elements)) + @result{} (use the words foo bar as elements) +@end group +@end example + +Emacs 18 had a bug which made the previous example fail. The bug +affected @code{,@@} followed only by constant elements. If you are +concerned with Emacs 18 compatibility, you can work around the bug like +this: + +@example +(` (use the words (,@@ (cdr list)) as elements @code{(,@@ nil)})) +@end example + +@noindent +@code{(,@@ nil)} avoids the problem by being a nonconstant element that +does not affect the result. + +@defmac ` list +This macro quotes @var{list} except for any sublists of the form +@code{(, @var{subexp})} or @code{(,@@ @var{listexp})}. Backquote +replaces these sublists with the value of @var{subexp} (as a single +element) or @var{listexp} (by splicing). Backquote copies the structure +of @var{list} down to the places where variable parts are substituted. + +@ignore @c these work now! +There are certain contexts in which @samp{,} would not be recognized and +should not be used: + +@smallexample +@group +;; @r{Use of a @samp{,} expression as the @sc{cdr} of a list.} +(` (a . (, 1))) ; @r{Not @code{(a . 1)}} + @result{} (a \, 1) +@end group + +@group +;; @r{Use of @samp{,} in a vector.} +(` [a (, 1) c]) ; @r{Not @code{[a 1 c]}} + @error{} Wrong type argument +@end group +@end smallexample +@end ignore +@end defmac + +@cindex CL note---@samp{,}, @samp{,@@} as functions +@quotation +@b{Common Lisp note:} in Common Lisp, @samp{,} and @samp{,@@} are implemented +as reader macros, so they do not require parentheses. Emacs Lisp implements +them as functions because reader macros are not supported (to save space). +@end quotation + +@node Problems with Macros +@section Common Problems Using Macros + + The basic facts of macro expansion have counterintuitive consequences. +This section describes some important consequences that can lead to +trouble, and rules to follow to avoid trouble. + +@menu +* Argument Evaluation:: The expansion should evaluate each macro arg once. +* Surprising Local Vars:: Local variable bindings in the expansion + require special care. +* Eval During Expansion:: Don't evaluate them; put them in the expansion. +* Repeated Expansion:: Avoid depending on how many times expansion is done. +@end menu + +@node Argument Evaluation +@subsection Evaluating Macro Arguments Repeatedly + + When defining a macro you must pay attention to the number of times +the arguments will be evaluated when the expansion is executed. The +following macro (used to facilitate iteration) illustrates the problem. +This macro allows us to write a simple ``for'' loop such as one might +find in Pascal. + +@findex for +@smallexample +@group +(defmacro for (var from init to final do &rest body) + "Execute a simple \"for\" loop. +For example, (for i from 1 to 10 do (print i))." + (list 'let (list (list var init)) + (cons 'while (cons (list '<= var final) + (append body (list (list 'inc var))))))) +@end group +@result{} for + +@group +(for i from 1 to 3 do + (setq square (* i i)) + (princ (format "\n%d %d" i square))) +@expansion{} +@end group +@group +(let ((i 1)) + (while (<= i 3) + (setq square (* i i)) + (princ (format "%d %d" i square)) + (inc i))) +@end group +@group + + @print{}1 1 + @print{}2 4 + @print{}3 9 +@result{} nil +@end group +@end smallexample + +@noindent +(The arguments @code{from}, @code{to}, and @code{do} in this macro are +``syntactic sugar''; they are entirely ignored. The idea is that you +will write noise words (such as @code{from}, @code{to}, and @code{do}) +in those positions in the macro call.) + +This macro suffers from the defect that @var{final} is evaluated on +every iteration. If @var{final} is a constant, this is not a problem. +If it is a more complex form, say @code{(long-complex-calculation x)}, +this can slow down the execution significantly. If @var{final} has side +effects, executing it more than once is probably incorrect. + +@cindex macro argument evaluation +A well-designed macro definition takes steps to avoid this problem by +producing an expansion that evaluates the argument expressions exactly +once unless repeated evaluation is part of the intended purpose of the +macro. Here is a correct expansion for the @code{for} macro: + +@smallexample +@group +(let ((i 1) + (max 3)) + (while (<= i max) + (setq square (* i i)) + (princ (format "%d %d" i square)) + (inc i))) +@end group +@end smallexample + +Here is a macro definition that creates this expansion: + +@smallexample +@group +(defmacro for (var from init to final do &rest body) + "Execute a simple for loop: (for i from 1 to 10 do (print i))." + (` (let (((, var) (, init)) + (max (, final))) + (while (<= (, var) max) + (,@@ body) + (inc (, var)))))) +@end group +@end smallexample + + Unfortunately, this introduces another problem. +@ifinfo +Proceed to the following node. +@end ifinfo + +@node Surprising Local Vars +@subsection Local Variables in Macro Expansions + +@ifinfo + In the previous section, the definition of @code{for} was fixed as +follows to make the expansion evaluate the macro arguments the proper +number of times: + +@smallexample +@group +(defmacro for (var from init to final do &rest body) + "Execute a simple for loop: (for i from 1 to 10 do (print i))." +@end group +@group + (` (let (((, var) (, init)) + (max (, final))) + (while (<= (, var) max) + (,@@ body) + (inc (, var)))))) +@end group +@end smallexample +@end ifinfo + + The new definition of @code{for} has a new problem: it introduces a +local variable named @code{max} which the user does not expect. This +causes trouble in examples such as the following: + +@example +@group +(let ((max 0)) + (for x from 0 to 10 do + (let ((this (frob x))) + (if (< max this) + (setq max this))))) +@end group +@end example + +@noindent +The references to @code{max} inside the body of the @code{for}, which +are supposed to refer to the user's binding of @code{max}, really access +the binding made by @code{for}. + +The way to correct this is to use an uninterned symbol instead of +@code{max} (@pxref{Creating Symbols}). The uninterned symbol can be +bound and referred to just like any other symbol, but since it is created +by @code{for}, we know that it cannot appear in the user's program. +Since it is not interned, there is no way the user can put it into the +program later. It will never appear anywhere except where put by +@code{for}. Here is a definition of @code{for} which works this way: + +@smallexample +@group +(defmacro for (var from init to final do &rest body) + "Execute a simple for loop: (for i from 1 to 10 do (print i))." + (let ((tempvar (make-symbol "max"))) + (` (let (((, var) (, init)) + ((, tempvar) (, final))) + (while (<= (, var) (, tempvar)) + (,@@ body) + (inc (, var))))))) +@end group +@end smallexample + +@noindent +This creates an uninterned symbol named @code{max} and puts it in the +expansion instead of the usual interned symbol @code{max} that appears +in expressions ordinarily. + +@node Eval During Expansion +@subsection Evaluating Macro Arguments in Expansion + + Another problem can happen if you evaluate any of the macro argument +expressions during the computation of the expansion, such as by calling +@code{eval} (@pxref{Eval}). If the argument is supposed to refer to the +user's variables, you may have trouble if the user happens to use a +variable with the same name as one of the macro arguments. Inside the +macro body, the macro argument binding is the most local binding of this +variable, so any references inside the form being evaluated do refer +to it. Here is an example: + +@example +@group +(defmacro foo (a) + (list 'setq (eval a) t)) + @result{} foo +@end group +@group +(setq x 'b) +(foo x) @expansion{} (setq b t) + @result{} t ; @r{and @code{b} has been set.} +;; @r{but} +(setq a 'c) +(foo a) @expansion{} (setq a t) + @result{} t ; @r{but this set @code{a}, not @code{c}.} + +@end group +@end example + + It makes a difference whether the user's variable is named @code{a} or +@code{x}, because @code{a} conflicts with the macro argument variable +@code{a}. + + Another reason not to call @code{eval} in a macro definition is that +it probably won't do what you intend in a compiled program. The +byte-compiler runs macro definitions while compiling the program, when +the program's own computations (which you might have wished to access +with @code{eval}) don't occur and its local variable bindings don't +exist. + + The safe way to work with the run-time value of an expression is to +put the expression into the macro expansion, so that its value is +computed as part of executing the expansion. + +@node Repeated Expansion +@subsection How Many Times is the Macro Expanded? + + Occasionally problems result from the fact that a macro call is +expanded each time it is evaluated in an interpreted function, but is +expanded only once (during compilation) for a compiled function. If the +macro definition has side effects, they will work differently depending +on how many times the macro is expanded. + + In particular, constructing objects is a kind of side effect. If the +macro is called once, then the objects are constructed only once. In +other words, the same structure of objects is used each time the macro +call is executed. In interpreted operation, the macro is reexpanded +each time, producing a fresh collection of objects each time. Usually +this does not matter---the objects have the same contents whether they +are shared or not. But if the surrounding program does side effects +on the objects, it makes a difference whether they are shared. Here is +an example: + +@lisp +@group +(defmacro empty-object () + (list 'quote (cons nil nil))) +@end group + +@group +(defun initialize (condition) + (let ((object (empty-object))) + (if condition + (setcar object condition)) + object)) +@end group +@end lisp + +@noindent +If @code{initialize} is interpreted, a new list @code{(nil)} is +constructed each time @code{initialize} is called. Thus, no side effect +survives between calls. If @code{initialize} is compiled, then the +macro @code{empty-object} is expanded during compilation, producing a +single ``constant'' @code{(nil)} that is reused and altered each time +@code{initialize} is called. + +One way to avoid pathological cases like this is to think of +@code{empty-object} as a funny kind of constant, not as a memory +allocation construct. You wouldn't use @code{setcar} on a constant such +as @code{'(nil)}, so naturally you won't use it on @code{(empty-object)} +either. 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 @@ +@c -*-texinfo-*- +@c This is part of the GNU Emacs Lisp Reference Manual. +@c Copyright (C) 1990, 1991, 1992, 1993, 1994 Free Software Foundation, Inc. +@c See the file elisp.texi for copying conditions. +@setfilename ../info/os +@node System Interface, Display, Processes, Top +@chapter Operating System Interface + + This chapter is about starting and getting out of Emacs, access to +values in the operating system environment, and terminal input, output +and flow control. + + @xref{Building Emacs}, for related information. See also +@ref{Display}, for additional operating system status information +pertaining to the terminal and the screen. + +@menu +* Starting Up:: Customizing Emacs start-up processing. +* Getting Out:: How exiting works (permanent or temporary). +* System Environment:: Distinguish the name and kind of system. +* User Identification:: Finding the name and user id of the user. +* Time of Day:: Getting the current time. +* Timers:: Setting a timer to call a function at a certain time. +* Terminal Input:: Recording terminal input for debugging. +* Terminal Output:: Recording terminal output for debugging. +* Special Keysyms:: Defining system-specific key symbols for X windows. +* Flow Control:: How to turn output flow control on or off. +* Batch Mode:: Running Emacs without terminal interaction. +@end menu + +@node Starting Up +@section Starting Up Emacs + + This section describes what Emacs does when it is started, and how you +can customize these actions. + +@menu +* Start-up Summary:: Sequence of actions Emacs performs at start-up. +* Init File:: Details on reading the init file (@file{.emacs}). +* Terminal-Specific:: How the terminal-specific Lisp file is read. +* Command Line Arguments:: How command line arguments are processed, + and how you can customize them. +@end menu + +@node Start-up Summary +@subsection Summary: Sequence of Actions at Start Up +@cindex initialization +@cindex start up of Emacs +@cindex @file{startup.el} + + The order of operations performed (in @file{startup.el}) by Emacs when +it is started up is as follows: + +@enumerate +@item +It loads the initialization library for the window system, if you are +using a window system. This library's name is +@file{term/@var{windowsystem}-win.el}. + +@item +It initializes the X window frame and faces, if appropriate. + +@item +It runs the normal hook @code{before-init-hook}. + +@item +It loads the library @file{site-start}, unless the option +@samp{-no-site-file} was specified. The library's file name is usually +@file{site-start.el}. +@cindex @file{site-start.el} + +@item +It loads the file @file{~/.emacs} unless @samp{-q} was specified on +command line. (This is not done in @samp{-batch} mode.) The @samp{-u} +option can specify the user name whose home directory should be used +instead of @file{~}. + +@item +It loads the library @file{default} unless @code{inhibit-default-init} +is non-@code{nil}. (This is not done in @samp{-batch} mode or if +@samp{-q} was specified on command line.) The library's file name is +usually @file{default.el}. +@cindex @file{default.el} + +@item +It runs the normal hook @code{after-init-hook}. + +@item +It sets the major mode according to @code{initial-major-mode}, provided +the buffer @samp{*scratch*} is still current and still in Fundamental +mode. + +@item +It loads the terminal-specific Lisp file, if any, except when in batch +mode or using a window system. + +@item +It displays the initial echo area message, unless you have suppressed +that with @code{inhibit-startup-echo-area-message}. + +@item +It processes any remaining command line arguments. + +@item +It runs @code{term-setup-hook}. + +@item +It calls @code{frame-notice-user-settings}, which modifies the +parameters of the selected frame according to whatever the init files +specify. + +@item +It runs @code{window-setup-hook}. @xref{Window Systems}. + +@item +It displays copyleft, nonwarranty and basic use information, provided +there were no remaining command line arguments (a few steps above) and +the value of @code{inhibit-startup-message} is @code{nil}. +@end enumerate + +@defopt inhibit-startup-message +This variable inhibits the initial startup messages (the nonwarranty, +etc.). If it is non-@code{nil}, then the messages are not printed. + +This variable exists so you can set it in your personal init file, once +you are familiar with the contents of the startup message. Do not set +this variable in the init file of a new user, or in a way that affects +more than one user, because that would prevent new users from receiving +the information they are supposed to see. +@end defopt + +@defopt inhibit-startup-echo-area-message +This variable controls the display of the startup echo area message. +You can suppress the startup echo area message by adding text with this +form to your @file{.emacs} file: + +@example +(setq inhibit-startup-echo-area-message + "@var{your-login-name}") +@end example + +Simply setting @code{inhibit-startup-echo-area-message} to your login +name is not sufficient to inhibit the message; Emacs explicitly checks +whether @file{.emacs} contains an expression as shown above. Your login +name must appear in the expression as a Lisp string constant. + +This way, you can easily inhibit the message for yourself if you wish, +but thoughtless copying of your @file{.emacs} file will not inhibit the +message for someone else. +@end defopt + +@node Init File +@subsection The Init File: @file{.emacs} +@cindex init file +@cindex @file{.emacs} + + When you start Emacs, it normally attempts to load the file +@file{.emacs} from your home directory. This file, if it exists, must +contain Lisp code. It is called your @dfn{init file}. The command line +switches @samp{-q} and @samp{-u} affect the use of the init file; +@samp{-q} says not to load an init file, and @samp{-u} says to load a +specified user's init file instead of yours. @xref{Entering Emacs, , , +emacs, The GNU Emacs Manual}. + +@cindex default init file + A site may have a @dfn{default init file}, which is the library named +@file{default.el}. Emacs finds the @file{default.el} file through the +standard search path for libraries (@pxref{How Programs Do Loading}). +The Emacs distribution does not come with this file; sites may provide +one for local customizations. If the default init file exists, it is +loaded whenever you start Emacs, except in batch mode or if @samp{-q} is +specified. But your own personal init file, if any, is loaded first; if +it sets @code{inhibit-default-init} to a non-@code{nil} value, then +Emacs does not subsequently load the @file{default.el} file. + + Another file for site-customization is @file{site-start.el}. Emacs +loads this @emph{before} the user's init file. You can inhibit the +loading of this file with the option @samp{-no-site-file}. + + If there is a great deal of code in your @file{.emacs} file, you +should move it into another file named @file{@var{something}.el}, +byte-compile it (@pxref{Byte Compilation}), and make your @file{.emacs} +file load the other file using @code{load} (@pxref{Loading}). + + @xref{Init File Examples, , , emacs, The GNU Emacs Manual}, for +examples of how to make various commonly desired customizations in your +@file{.emacs} file. + +@defopt inhibit-default-init +This variable prevents Emacs from loading the default initialization +library file for your session of Emacs. If its value is non-@code{nil}, +then the default library is not loaded. The default value is +@code{nil}. +@end defopt + +@defvar before-init-hook +@defvarx after-init-hook +These two normal hooks are run just before, and just after, loading of +the user's init file, @file{default.el}, and/or @file{site-start.el}. +@end defvar + +@node Terminal-Specific +@subsection Terminal-Specific Initialization +@cindex terminal-specific initialization + + Each terminal type can have its own Lisp library that Emacs loads when +run on that type of terminal. For a terminal type named @var{termtype}, +the library is called @file{term/@var{termtype}}. Emacs finds the file +by searching the @code{load-path} directories as it does for other +files, and trying the @samp{.elc} and @samp{.el} suffixes. Normally, +terminal-specific Lisp library is located in @file{emacs/lisp/term}, a +subdirectory of the @file{emacs/lisp} directory in which most Emacs Lisp +libraries are kept.@refill + + The library's name is constructed by concatenating the value of the +variable @code{term-file-prefix} and the terminal type. Normally, +@code{term-file-prefix} has the value @code{"term/"}; changing this +is not recommended. + + The usual function of a terminal-specific library is to enable special +keys to send sequences that Emacs can recognize. It may also need to +set or add to @code{function-key-map} if the Termcap entry does not +specify all the terminal's function keys. @xref{Terminal Input}. + +@cindex Termcap + When the name of the terminal type contains a hyphen, only the part of +the name before the first hyphen is significant in choosing the library +name. Thus, terminal types @samp{aaa-48} and @samp{aaa-30-rv} both use +the @file{term/aaa} library. If necessary, the library can evaluate +@code{(getenv "TERM")} to find the full name of the terminal +type.@refill + + Your @file{.emacs} file can prevent the loading of the +terminal-specific library by setting the variable +@code{term-file-prefix} to @code{nil}. This feature is useful when +experimenting with your own peculiar customizations. + + You can also arrange to override some of the actions of the +terminal-specific library by setting the variable +@code{term-setup-hook}. This is a normal hook which Emacs runs using +@code{run-hooks} at the end of Emacs initialization, after loading both +your @file{.emacs} file and any terminal-specific libraries. You can +use this variable to define initializations for terminals that do not +have their own libraries. @xref{Hooks}. + +@defvar term-file-prefix +@cindex @code{TERM} environment variable +If the @code{term-file-prefix} variable is non-@code{nil}, Emacs loads +a terminal-specific initialization file as follows: + +@example +(load (concat term-file-prefix (getenv "TERM"))) +@end example + +@noindent +You may set the @code{term-file-prefix} variable to @code{nil} in your +@file{.emacs} file if you do not wish to load the +terminal-initialization file. To do this, put the following in +your @file{.emacs} file: @code{(setq term-file-prefix nil)}. +@end defvar + +@defvar term-setup-hook +This variable is a normal hook which Emacs runs after loading your +@file{.emacs} file, the default initialization file (if any) and the +terminal-specific Lisp file. + +You can use @code{term-setup-hook} to override the definitions made by a +terminal-specific file. +@end defvar + + See @code{window-setup-hook} in @ref{Window Systems}, for a related +feature. + +@node Command Line Arguments +@subsection Command Line Arguments +@cindex command line arguments + + You can use command line arguments to request various actions when you +start Emacs. Since you do not need to start Emacs more than once per +day, and will often leave your Emacs session running longer than that, +command line arguments are hardly ever used. As a practical matter, it +is best to avoid making the habit of using them, since this habit would +encourage you to kill and restart Emacs unnecessarily often. These +options exist for two reasons: to be compatible with other editors (for +invocation by other programs) and to enable shell scripts to run +specific Lisp programs. + + This section describes how Emacs processes command line arguments, +and how you can customize them. + +@ignore + (Note that some other editors require you to start afresh each time +you want to edit a file. With this kind of editor, you will probably +specify the file as a command line argument. The recommended way to +use GNU Emacs is to start it only once, just after you log in, and do +all your editing in the same Emacs process. Each time you want to edit +a different file, you visit it with the existing Emacs, which eventually +comes to have many files in it ready for editing. Usually you do not +kill the Emacs until you are about to log out.) +@end ignore + +@defun command-line +This function parses the command line which Emacs was called with, +processes it, loads the user's @file{.emacs} file and displays the +initial nonwarranty information, etc. +@end defun + +@defvar command-line-processed +The value of this variable is @code{t} once the command line has been +processed. + +If you redump Emacs by calling @code{dump-emacs}, you may wish to set +this variable to @code{nil} first in order to cause the new dumped Emacs +to process its new command line arguments. +@end defvar + +@defvar command-switch-alist +@cindex switches on command line +@cindex options on command line +@cindex command line options +The value of this variable is an alist of user-defined command-line +options and associated handler functions. This variable exists so you +can add elements to it. + +A @dfn{command line option} is an argument on the command line of the +form: + +@example +-@var{option} +@end example + +The elements of the @code{command-switch-alist} look like this: + +@example +(@var{option} . @var{handler-function}) +@end example + +The @var{handler-function} is called to handle @var{option} and receives +the option name as its sole argument. + +In some cases, the option is followed in the command line by an +argument. In these cases, the @var{handler-function} can find all the +remaining command-line arguments in the variable +@code{command-line-args-left}. (The entire list of command-line +arguments is in @code{command-line-args}.) + +The command line arguments are parsed by the @code{command-line-1} +function in the @file{startup.el} file. See also @ref{Command +Switches, , Command Line Switches and Arguments, emacs, The GNU Emacs +Manual}. +@end defvar + +@defvar command-line-args +The value of this variable is the list of command line arguments passed +to Emacs. +@end defvar + +@defvar command-line-functions +This variable's value is a list of functions for handling an +unrecognized command-line argument. Each time the next argument to be +processed has no special meaning, the functions in this list are called, +in the order they appear, until one of them returns a non-@code{nil} +value. + +These functions are called with no arguments. They can access the +command-line argument under consideration through the variable +@code{argi}. The remaining arguments (not including the current one) +are in the variable @code{command-line-args-left}. + +When a function recognizes and processes the argument in @code{argi}, it +should return a non-@code{nil} value to say it has dealt with that +argument. If it has also dealt with some of the following arguments, it +can indicate that by deleting them from @code{command-line-args-left}. + +If all of these functions return @code{nil}, then the argument is used +as a file name to visit. +@end defvar + +@node Getting Out +@section Getting Out of Emacs +@cindex exiting Emacs + + There are two ways to get out of Emacs: you can kill the Emacs job, +which exits permanently, or you can suspend it, which permits you to +reenter the Emacs process later. As a practical matter, you seldom kill +Emacs---only when you are about to log out. Suspending is much more +common. + +@menu +* Killing Emacs:: Exiting Emacs irreversibly. +* Suspending Emacs:: Exiting Emacs reversibly. +@end menu + +@node Killing Emacs +@comment node-name, next, previous, up +@subsection Killing Emacs +@cindex killing Emacs + + Killing Emacs means ending the execution of the Emacs process. The +parent process normally resumes control. The low-level primitive for +killing Emacs is @code{kill-emacs}. + +@defun kill-emacs &optional exit-data +This function exits the Emacs process and kills it. + +If @var{exit-data} is an integer, then it is used as the exit status +of the Emacs process. (This is useful primarily in batch operation; see +@ref{Batch Mode}.) + +If @var{exit-data} is a string, its contents are stuffed into the +terminal input buffer so that the shell (or whatever program next reads +input) can read them. +@end defun + + All the information in the Emacs process, aside from files that have +been saved, is lost when the Emacs is killed. Because killing Emacs +inadvertently can lose a lot of work, Emacs queries for confirmation +before actually terminating if you have buffers that need saving or +subprocesses that are running. This is done in the function +@code{save-buffers-kill-emacs}. + +@defvar kill-emacs-query-functions +After asking the standard questions, @code{save-buffers-kill-emacs} +calls the functions in the list @code{kill-buffer-query-functions}, in +order of appearance, with no arguments. These functions can ask for +additional confirmation from the user. If any of them returns +non-@code{nil}, Emacs is not killed. +@end defvar + +@defvar kill-emacs-hook +This variable is a normal hook; once @code{save-buffers-kill-emacs} is +finished with all file saving and confirmation, it runs the functions in +this hook. +@end defvar + +@node Suspending Emacs +@subsection Suspending Emacs +@cindex suspending Emacs + + @dfn{Suspending Emacs} means stopping Emacs temporarily and returning +control to its superior process, which is usually the shell. This +allows you to resume editing later in the same Emacs process, with the +same buffers, the same kill ring, the same undo history, and so on. To +resume Emacs, use the appropriate command in the parent shell---most +likely @code{fg}. + + Some operating systems do not support suspension of jobs; on these +systems, ``suspension'' actually creates a new shell temporarily as a +subprocess of Emacs. Then you would exit the shell to return to Emacs. + + Suspension is not useful with window systems such as X, because the +Emacs job may not have a parent that can resume it again, and in any +case you can give input to some other job such as a shell merely by +moving to a different window. Therefore, suspending is not allowed +when Emacs is an X client. + +@defun suspend-emacs string +This function stops Emacs and returns control to the superior process. +If and when the superior process resumes Emacs, @code{suspend-emacs} +returns @code{nil} to its caller in Lisp. + +If @var{string} is non-@code{nil}, its characters are sent to be read +as terminal input by Emacs's superior shell. The characters in +@var{string} are not echoed by the superior shell; only the results +appear. + +Before suspending, @code{suspend-emacs} runs the normal hook +@code{suspend-hook}. In Emacs version 18, @code{suspend-hook} was not a +normal hook; its value was a single function, and if its value was +non-@code{nil}, then @code{suspend-emacs} returned immediately without +actually suspending anything. + +After the user resumes Emacs, it runs the normal hook +@code{suspend-resume-hook}. @xref{Hooks}. + +The next redisplay after resumption will redraw the entire screen, +unless the variable @code{no-redraw-on-reenter} is non-@code{nil} +(@pxref{Refresh Screen}). + +In the following example, note that @samp{pwd} is not echoed after +Emacs is suspended. But it is read and executed by the shell. + +@smallexample +@group +(suspend-emacs) + @result{} nil +@end group + +@group +(add-hook 'suspend-hook + (function (lambda () + (or (y-or-n-p + "Really suspend? ") + (error "Suspend cancelled"))))) + @result{} (lambda nil + (or (y-or-n-p "Really suspend? ") + (error "Suspend cancelled"))) +@end group +@group +(add-hook 'suspend-resume-hook + (function (lambda () (message "Resumed!")))) + @result{} (lambda nil (message "Resumed!")) +@end group +@group +(suspend-emacs "pwd") + @result{} nil +@end group +@group +---------- Buffer: Minibuffer ---------- +Really suspend? @kbd{y} +---------- Buffer: Minibuffer ---------- +@end group + +@group +---------- Parent Shell ---------- +lewis@@slug[23] % /user/lewis/manual +lewis@@slug[24] % fg +@end group + +@group +---------- Echo Area ---------- +Resumed! +@end group +@end smallexample +@end defun + +@defvar suspend-hook +This variable is a normal hook run before suspending. +@end defvar + +@defvar suspend-resume-hook +This variable is a normal hook run after suspending. +@end defvar + +@node System Environment +@section Operating System Environment +@cindex operating system environment + + Emacs provides access to variables in the operating system environment +through various functions. These variables include the name of the +system, the user's @sc{uid}, and so on. + +@defvar system-type +The value of this variable is a symbol indicating the type of +operating system Emacs is operating on. Here is a table of the symbols +for the operating systems that Emacs can run on up to version 19.1. + +@table @code +@item aix-v3 +AIX. + +@item berkeley-unix +Berkeley BSD. + +@item hpux +Hewlett-Packard operating system. + +@item irix +Silicon Graphics Irix system. + +@item rtu +Masscomp RTU, UCB universe. + +@item unisoft-unix +UniSoft UniPlus. + +@item usg-unix-v +AT&T System V. + +@item vax-vms +VAX VMS. + +@item xenix +SCO Xenix 386. +@end table + +We do not wish to add new symbols to make finer distinctions unless it +is absolutely necessary! In fact, we hope to eliminate some of these +alternatives in the future. We recommend using +@code{system-configuration} to distinguish between different operating +systems. +@end defvar + +@defvar system-configuration +This variable holds the three-part configuration name for the +hardware/software configuration of your system, as a string. The +convenient way to test parts of this string is with @code{string-match}. +@end defvar + +@defun system-name +This function returns the name of the machine you are running on. +@example +(system-name) + @result{} "prep.ai.mit.edu" +@end example +@end defun + +@defun getenv var +@cindex environment variable access +This function returns the value of the environment variable @var{var}, +as a string. Within Emacs, the environment variable values are kept in +the Lisp variable @code{process-environment}. + +@example +@group +(getenv "USER") + @result{} "lewis" +@end group + +@group +lewis@@slug[10] % printenv +PATH=.:/user/lewis/bin:/usr/bin:/usr/local/bin +USER=lewis +@end group +@group +TERM=ibmapa16 +SHELL=/bin/csh +HOME=/user/lewis +@end group +@end example +@end defun + +@c Emacs 19 feature +@deffn Command setenv variable value +This command sets the value of the environment variable named +@var{variable} to @var{value}. Both arguments should be strings. This +function works by modifying @code{process-environment}; binding that +variable with @code{let} is also reasonable practice. +@end deffn + +@defvar process-environment +This variable is a list of strings, each describing one environment +variable. The functions @code{getenv} and @code{setenv} work by means +of this variable. + +@smallexample +@group +process-environment +@result{} ("l=/usr/stanford/lib/gnuemacs/lisp" + "PATH=.:/user/lewis/bin:/usr/class:/nfsusr/local/bin" + "USER=lewis" +@end group +@group + "TERM=ibmapa16" + "SHELL=/bin/csh" + "HOME=/user/lewis") +@end group +@end smallexample +@end defvar + +@defun load-average +This function returns the current 1 minute, 5 minute and 15 minute +load averages in a list. The values are integers that are 100 times +the system load averages. (The load averages indicate the number of +processes trying to run.) + +@example +@group +(load-average) + @result{} (169 48 36) +@end group + +@group +lewis@@rocky[5] % uptime + 11:55am up 1 day, 19:37, 3 users, + load average: 1.69, 0.48, 0.36 +@end group +@end example +@end defun + +@defun emacs-pid +This function returns the process @sc{id} of the Emacs process. +@end defun + +@defun setprv privilege-name &optional setp getprv +This function sets or resets a VMS privilege. (It does not exist on +Unix.) The first arg is the privilege name, as a string. The second +argument, @var{setp}, is @code{t} or @code{nil}, indicating whether the +privilege is to be turned on or off. Its default is @code{nil}. The +function returns @code{t} if successful, @code{nil} otherwise. + + If the third argument, @var{getprv}, is non-@code{nil}, @code{setprv} +does not change the privilege, but returns @code{t} or @code{nil} +indicating whether the privilege is currently enabled. +@end defun + +@node User Identification +@section User Identification + +@defun user-login-name +This function returns the name under which the user is logged in. If +the environment variable @code{LOGNAME} is set, that value is used. +Otherwise, if the environment variable @code{USER} is set, that value is +used. Otherwise, the value is based on the effective @sc{uid}, not the +real @sc{uid}. + +@example +@group +(user-login-name) + @result{} "lewis" +@end group +@end example +@end defun + +@defun user-real-login-name +This function returns the user name corresponding to Emacs's real +@sc{uid}. This ignores the effective @sc{uid} and ignores the +environment variables @code{LOGNAME} and @code{USER}. +@end defun + +@defun user-full-name +This function returns the full name of the user. + +@example +@group +(user-full-name) + @result{} "Bil Lewis" +@end group +@end example +@end defun + +@defun user-real-uid +This function returns the real @sc{uid} of the user. + +@example +@group +(user-real-uid) + @result{} 19 +@end group +@end example +@end defun + +@defun user-uid +This function returns the effective @sc{uid} of the user. +@end defun + +@node Time of Day +@section Time of Day + + This section explains how to determine the current time and the time +zone. + +@defun current-time-string &optional time-value +This function returns the current time and date as a humanly-readable +string. The format of the string is unvarying; the number of characters +used for each part is always the same, so you can reliably use +@code{substring} to extract pieces of it. However, it would be wise to +count the characters from the beginning of the string rather than from +the end, as additional information may be added at the end. + +@c Emacs 19 feature +The argument @var{time-value}, if given, specifies a time to format +instead of the current time. The argument should be a cons cell +containing two integers, or a list whose first two elements are +integers. Thus, you can use times obtained from @code{current-time} +(see below) and from @code{file-attributes} (@pxref{File Attributes}). + +@example +@group +(current-time-string) + @result{} "Wed Oct 14 22:21:05 1987" +@end group +@end example +@end defun + +@c Emacs 19 feature +@defun current-time +This function returns the system's time value as a list of three +integers: @code{(@var{high} @var{low} @var{microsec})}. The integers +@var{high} and @var{low} combine to give the number of seconds since +0:00 January 1, 1970, which is +@ifinfo +@var{high} * 2**16 + @var{low}. +@end ifinfo +@tex +$high*-2^{16}+low$. +@end tex + +The third element, @var{microsec}, gives the microseconds since the +start of the current second (or 0 for systems that return time only on +the resolution of a second). + +The first two elements can be compared with file time values such as you +get with the function @code{file-attributes}. @xref{File Attributes}. +@end defun + +@c Emacs 19 feature +@defun current-time-zone &optional time-value +This function returns a list describing the time zone that the user is +in. + +The value has the form @code{(@var{offset} @var{name})}. Here +@var{offset} is an integer giving the number of seconds ahead of UTC +(east of Greenwich). A negative value means west of Greenwich. The +second element, @var{name} is a string giving the name of the time +zone. Both elements change when daylight savings time begins or ends; +if the user has specified a time zone that does not use a seasonal time +adjustment, then the value is constant through time. + +If the operating system doesn't supply all the information necessary to +compute the value, both elements of the list are @code{nil}. + +The argument @var{time-value}, if given, specifies a time to analyze +instead of the current time. The argument should be a cons cell +containing two integers, or a list whose first two elements are +integers. Thus, you can use times obtained from @code{current-time} +(see below) and from @code{file-attributes} (@pxref{File Attributes}). +@end defun + +@node Timers +@section Timers + +You can set up a timer to call a function at a specified future time. + +@defun run-at-time time repeat function &rest args +This function arranges to call @var{function} with arguments @var{args} +at time @var{time}. The argument @var{function} is a function to call +later, and @var{args} are the arguments to give it when it is called. +The time @var{time} is specified as a string. + +Absolute times may be specified in a wide variety of formats; The form +@samp{@var{hour}:@var{min}:@var{sec} @var{timezone} +@var{month}/@var{day}/@var{year}}, where all fields are numbers, works; +the format that @code{current-time-string} returns is also allowed. + +To specify a relative time, use numbers followed by units. +For example: + +@table @samp +@item 1 min +denotes 1 minute from now. +@item 1 min 5 sec +denotes 65 seconds from now. +@item 1 min 2 sec 3 hour 4 day 5 week 6 fortnight 7 month 8 year +denotes exactly 103 months, 123 days, and 10862 seconds from now. +@end table + +If @var{time} is an integer, that specifies a relative time measured in +seconds. + +The argument @var{repeat} specifies how often to repeat the call. If +@var{repeat} is @code{nil}, there are no repetitions; @var{function} is +called just once, at @var{time}. If @var{repeat} is an integer, it +specifies a repetition period measured in seconds. +@end defun + +@defun cancel-timer timer +Cancel the requested action for @var{timer}, which should be a value +previously returned by @code{run-at-time}. This cancels the effect of +that call to @code{run-at-time}; the arrival of the specified time will +not cause anything special to happen. +@end defun + +@node Terminal Input +@section Terminal Input +@cindex terminal input + + This section describes functions and variables for recording or +manipulating terminal input. See @ref{Display}, for related +functions. + +@menu +* Input Modes:: Options for how input is processed. +* Translating Input:: Low level conversion of some characters or events + into others. +* Recording Input:: Saving histories of recent or all input events. +@end menu + +@node Input Modes +@subsection Input Modes +@cindex input modes +@cindex terminal input modes + +@defun set-input-mode interrupt flow meta quit-char +This function sets the mode for reading keyboard input. If +@var{interrupt} is non-null, then Emacs uses input interrupts. If it is +@code{nil}, then it uses @sc{cbreak} mode. + +If @var{flow} is non-@code{nil}, then Emacs uses @sc{xon/xoff} (@kbd{C-q}, +@kbd{C-s}) flow control for output to terminal. This has no effect except +in @sc{cbreak} mode. @xref{Flow Control}. + +The default setting is system dependent. Some systems always use +@sc{cbreak} mode regardless of what is specified. + +@c Emacs 19 feature +The argument @var{meta} controls support for input character codes +above 127. If @var{meta} is @code{t}, Emacs converts characters with +the 8th bit set into Meta characters. If @var{meta} is @code{nil}, +Emacs disregards the 8th bit; this is necessary when the terminal uses +it as a parity bit. If @var{meta} is neither @code{t} nor @code{nil}, +Emacs uses all 8 bits of input unchanged. This is good for terminals +using European 8-bit character sets. + +@c Emacs 19 feature +If @var{quit-char} is non-@code{nil}, it specifies the character to +use for quitting. Normally this character is @kbd{C-g}. +@xref{Quitting}. +@end defun + +The @code{current-input-mode} function returns the input mode settings +Emacs is currently using. + +@c Emacs 19 feature +@defun current-input-mode +This function returns current mode for reading keyboard input. It +returns a list, corresponding to the arguments of @code{set-input-mode}, +of the form @code{(@var{interrupt} @var{flow} @var{meta} @var{quit})} in +which: +@table @var +@item interrupt +is non-@code{nil} when Emacs is using interrupt-driven input. If +@code{nil}, Emacs is using @sc{cbreak} mode. +@item flow +is non-@code{nil} if Emacs uses @sc{xon/xoff} (@kbd{C-q}, @kbd{C-s}) +flow control for output to the terminal. This value has no effect +unless @var{interrupt} is non-@code{nil}. +@item meta +is non-@code{t} if Emacs treats the eighth bit of input characters as +the meta bit; @code{nil} means Emacs clears the eighth bit of every +input character; any other value means Emacs uses all eight bits as the +basic character code. +@item quit +is the character Emacs currently uses for quitting, usually @kbd{C-g}. +@end table +@end defun + +@defvar meta-flag +This variable used to control whether to treat the eight bit in keyboard +input characters as the @key{Meta} bit. @code{nil} meant no, and +anything else meant yes. This variable existed in Emacs versions 18 and +earlier but no longer exists in Emacs 19; use @code{set-input-mode} +instead. +@end defvar + +@node Translating Input +@subsection Translating Input Events +@cindex translating input events + + This section describes features for translating input events into other +input events before they become part of key sequences. + +@c Emacs 19 feature +@defvar extra-keyboard-modifiers +This variable lets Lisp programs ``press'' the modifier keys on the +keyboard. The value is a bit mask: + +@table @asis +@item 1 +The @key{SHIFT} key. +@item 2 +The @key{LOCK} key. +@item 4 +The @key{CTL} key. +@item 8 +The @key{META} key. +@end table + +Each time the user types a keyboard key, it is altered as if the +modifier keys specified in the bit mask were held down. + +When you use X windows, the program can ``press'' any of the modifier +keys in this way. Otherwise, only the @key{CTL} and @key{META} keys can +be virtually pressed. +@end defvar + +@defvar keyboard-translate-table +This variable is the translate table for keyboard characters. It lets +you reshuffle the keys on the keyboard without changing any command +bindings. Its value must be a string or @code{nil}. + +If @code{keyboard-translate-table} is a string, then each character read +from the keyboard is looked up in this string and the character in the +string is used instead. If the string is of length @var{n}, character codes +@var{n} and up are untranslated. + +In the example below, we set @code{keyboard-translate-table} to a +string of 128 characters. Then we fill it in to swap the characters +@kbd{C-s} and @kbd{C-\} and the characters @kbd{C-q} and @kbd{C-^}. +Subsequently, typing @kbd{C-\} has all the usual effects of typing +@kbd{C-s}, and vice versa. (@xref{Flow Control} for more information on +this subject.) + +@cindex flow control example +@example +@group +(defun evade-flow-control () + "Replace C-s with C-\ and C-q with C-^." + (interactive) +@end group +@group + (let ((the-table (make-string 128 0))) + (let ((i 0)) + (while (< i 128) + (aset the-table i i) + (setq i (1+ i)))) +@end group + ;; @r{Swap @kbd{C-s} and @kbd{C-\}.} + (aset the-table ?\034 ?\^s) + (aset the-table ?\^s ?\034) +@group + ;; @r{Swap @kbd{C-q} and @kbd{C-^}.} + (aset the-table ?\036 ?\^q) + (aset the-table ?\^q ?\036) + (setq keyboard-translate-table the-table))) +@end group +@end example + +Note that this translation is the first thing that happens to a +character after it is read from the terminal. Record-keeping features +such as @code{recent-keys} and dribble files record the characters after +translation. +@end defvar + +@defun keyboard-translate from to +This function modifies @code{keyboard-translate-table} to translate +character code @var{from} into character code @var{to}. It creates +or enlarges the translate table if necessary. +@end defun + +@defvar function-key-map +This variable holds a keymap which describes the character sequences +sent by function keys on an ordinary character terminal. This keymap +uses the data structure as other keymaps, but is used differently: it +specifies translations to make while reading events. + +If @code{function-key-map} ``binds'' a key sequence @var{k} to a vector +@var{v}, then when @var{k} appears as a subsequence @emph{anywhere} in a +key sequence, it is replaced with the events in @var{v}. + +For example, VT100 terminals send @kbd{@key{ESC} O P} when the +keypad PF1 key is pressed. Therefore, we want Emacs to translate +that sequence of events into the single event @code{pf1}. We accomplish +this by ``binding'' @kbd{@key{ESC} O P} to @code{[pf1]} in +@code{function-key-map}, when using a VT100. + +Thus, typing @kbd{C-c @key{PF1}} sends the character sequence @kbd{C-c +@key{ESC} O P}; later the function @code{read-key-sequence} translates +this back into @kbd{C-c @key{PF1}}, which it returns as the vector +@code{[?\C-c pf1]}. + +Entries in @code{function-key-map} are ignored if they conflict with +bindings made in the minor mode, local, or global keymaps. The intent +is that the character sequences that function keys send should not have +command bindings in their own right. + +The value of @code{function-key-map} is usually set up automatically +according to the terminal's Terminfo or Termcap entry, but sometimes +those need help from terminal-specific Lisp files. Emacs comes with +terminal-specific files for many common terminals; their main purpose is +to make entries in @code{function-key-map} beyond those that can be +deduced from Termcap and Terminfo. @xref{Terminal-Specific}. + +Emacs versions 18 and earlier used totally different means of detecting +the character sequences that represent function keys. +@end defvar + +@defvar key-translation-map +This variable is another keymap used just like @code{function-key-map} +to translate input events into other events. It differs from +@code{function-key-map} in two ways: + +@itemize @bullet +@item +@code{key-translation-map} goes to work after @code{function-key-map} is +finished; it receives the results of translation by +@code{function-key-map}. + +@item +@code{key-translation-map} overrides actual key bindings. +@end itemize + +The intent of @code{key-translation-map} is for users to map one +character set to another, including ordinary characters normally bound +to @code{self-insert-command}. +@end defvar + +@cindex key translation function +You can use @code{function-key-map} or @code{key-translation-map} for +more than simple aliases, by using a function, instead of a key +sequence, as the ``translation'' of a key. Then this function is called +to compute the translation of that key. + +The key translation function receives one argument, which is the prompt +that was specified in @code{read-key-sequence}---or @code{nil} if the +key sequence is being read by the editor command loop. In most cases +you can ignore the prompt value. + +If the function reads input itself, it can have the effect of altering +the event that follows. For example, here's how to define @kbd{C-c h} +to turn the character that follows into a Hyper character: + +@example +(defun hyperify (prompt) + (let ((e (read-event))) + (vector (if (numberp e) + (logior (lsh 1 20) e) + (if (memq 'hyper (event-modifiers e)) + e + (add-event-modifier "H-" e)))))) + +(defun add-event-modifier (string e) + (let ((symbol (if (symbolp e) e (car e)))) + (setq symbol (intern (concat string + (symbol-name symbol)))) + (if (symbolp e) + symbol + (cons symbol (cdr e))))) + +(define-key function-key-map "\C-ch" 'hyperify) +@end example + +@pindex iso-transl +@cindex Latin-1 character set (input) +@cindex ISO Latin-1 characters (input) +The @file{iso-transl} library uses this feature to provide a way of +inputting non-ASCII Latin-1 characters. + +@node Recording Input +@subsection Recording Input + +@defun recent-keys +This function returns a vector containing the last 100 input events +from the keyboard or mouse. All input events are included, whether or +not they were used as parts of key sequences. Thus, you always get the +last 100 inputs, not counting keyboard macros. (Events from keyboard +macros are excluded because they are less interesting for debugging; it +should be enough to see the events which invoked the macros.) +@end defun + +@deffn Command open-dribble-file filename +@cindex dribble file +This function opens a @dfn{dribble file} named @var{filename}. When a +dribble file is open, each input event from the keyboard or mouse (but +not those from keyboard macros) is written in that file. A +non-character event is expressed using its printed representation +surrounded by @samp{<@dots{}>}. + +You close the dribble file by calling this function with an argument +of @code{nil}. + +This function is normally used to record the input necessary to +trigger an Emacs bug, for the sake of a bug report. + +@example +@group +(open-dribble-file "~/dribble") + @result{} nil +@end group +@end example +@end deffn + + See also the @code{open-termscript} function (@pxref{Terminal Output}). + +@node Terminal Output +@section Terminal Output +@cindex terminal output + + The terminal output functions send output to the terminal or keep +track of output sent to the terminal. The variable @code{baud-rate} +tells you what Emacs thinks is the output speed of the terminal. + +@defvar baud-rate +This variable's value is the output speed of the terminal, as far as +Emacs knows. Setting this variable does not change the speed of actual +data transmission, but the value is used for calculations such as +padding. It also affects decisions about whether to scroll part of the +screen or repaint---even when using a window system, (We designed it +this way despite the fact that a window system has no true ``output +speed'', to give you a way to tune these decisions.) + +The value is measured in baud. +@end defvar + + If you are running across a network, and different parts of the +network work at different baud rates, the value returned by Emacs may be +different from the value used by your local terminal. Some network +protocols communicate the local terminal speed to the remote machine, so +that Emacs and other programs can get the proper value, but others do +not. If Emacs has the wrong value, it makes decisions that are less +than optimal. To fix the problem, set @code{baud-rate}. + +@defun baud-rate +This function returns the value of the variable @code{baud-rate}. In +Emacs versions 18 and earlier, this was the only way to find out the +terminal speed. +@end defun + +@defun send-string-to-terminal string +This function sends @var{string} to the terminal without alteration. +Control characters in @var{string} have terminal-dependent effects. + +One use of this function is to define function keys on terminals that +have downloadable function key definitions. For example, this is how on +certain terminals to define function key 4 to move forward four +characters (by transmitting the characters @kbd{C-u C-f} to the +computer): + +@example +@group +(send-string-to-terminal "\eF4\^U\^F") + @result{} nil +@end group +@end example +@end defun + +@deffn Command open-termscript filename +@cindex termscript file +This function is used to open a @dfn{termscript file} that will record +all the characters sent by Emacs to the terminal. It returns +@code{nil}. Termscript files are useful for investigating problems +where Emacs garbles the screen, problems that are due to incorrect +Termcap entries or to undesirable settings of terminal options more +often than to actual Emacs bugs. Once you are certain which characters +were actually output, you can determine reliably whether they correspond +to the Termcap specifications in use. + +See also @code{open-dribble-file} in @ref{Terminal Input}. + +@example +@group +(open-termscript "../junk/termscript") + @result{} nil +@end group +@end example +@end deffn + +@node Special Keysyms +@section System-Specific X11 Keysyms + +To define system-specific X11 keysyms, set the variable +@code{system-key-alist}. + +@defvar system-key-alist +This variable's value should be an alist with one element for each +system-specific keysym. An element has this form: @code{(@var{code} +. @var{symbol})}, where @var{code} is the numeric keysym code (not +including the ``vendor specific'' bit, 1 << 28), and @var{symbol} is the +name for the function key. + +For example @code{(168 . mute-acute)} defines a system-specific key used +by HP X servers whose numeric code is (1 << 28) + 168. + +It is not a problem if the alist defines keysyms for other X servers, as +long as they don't conflict with the ones used by the X server actually +in use. +@end defvar + +@node Flow Control +@section Flow Control +@cindex flow control characters + + This section attempts to answer the question ``Why does Emacs choose +to use flow-control characters in its command character set?'' For a +second view on this issue, read the comments on flow control in the +@file{emacs/INSTALL} file from the distribution; for help with Termcap +entries and DEC terminal concentrators, see @file{emacs/etc/TERMS}. + +@cindex @kbd{C-s} +@cindex @kbd{C-q} + At one time, most terminals did not need flow control, and none used +@code{C-s} and @kbd{C-q} for flow control. Therefore, the choice of +@kbd{C-s} and @kbd{C-q} as command characters was uncontroversial. +Emacs, for economy of keystrokes and portability, used nearly all the +@sc{ASCII} control characters, with mnemonic meanings when possible; +thus, @kbd{C-s} for search and @kbd{C-q} for quote. + + Later, some terminals were introduced which required these characters +for flow control. They were not very good terminals for full-screen +editing, so Emacs maintainers did not pay attention. In later years, +flow control with @kbd{C-s} and @kbd{C-q} became widespread among +terminals, but by this time it was usually an option. And the majority +of users, who can turn flow control off, were unwilling to switch to +less mnemonic key bindings for the sake of flow control. + + So which usage is ``right'', Emacs's or that of some terminal and +concentrator manufacturers? This question has no simple answer. + + One reason why we are reluctant to cater to the problems caused by +@kbd{C-s} and @kbd{C-q} is that they are gratuitous. There are other +techniques (albeit less common in practice) for flow control that +preserve transparency of the character stream. Note also that their use +for flow control is not an official standard. Interestingly, on the +model 33 teletype with a paper tape punch (which is very old), @kbd{C-s} +and @kbd{C-q} were sent by the computer to turn the punch on and off! + + GNU Emacs version 19 provides a convenient way of enabling flow +control if you want it: call the function @code{enable-flow-control}. + +@defun enable-flow-control +This function enables use of @kbd{C-s} and @kbd{C-q} for output flow +control, and provides the characters @kbd{C-\} and @kbd{C-^} as aliases +for them using @code{keyboard-translate-table} (@pxref{Translating Input}). +@end defun + +You can use the function @code{enable-flow-control-on} in your +@file{.emacs} file to enable flow control automatically on certain +terminal types. + +@defun enable-flow-control-on &rest termtypes +This function enables flow control, and the aliases @kbd{C-\} and @kbd{C-^}, +if the terminal type is one of @var{termtypes}. For example: + +@smallexample +(enable-flow-control-on "vt200" "vt300" "vt101" "vt131") +@end smallexample +@end defun + + Here is how @code{enable-flow-control} does its job: + +@enumerate +@item +@cindex @sc{cbreak} +It sets @sc{cbreak} mode for terminal input, and tells the operating +system to handle flow control, with @code{(set-input-mode nil t)}. + +@item +It sets up @code{keyboard-translate-table} to translate @kbd{C-\} and +@kbd{C-^} into @kbd{C-s} and @kbd{C-q} were typed. Except at its very +lowest level, Emacs never knows that the characters typed were anything +but @kbd{C-s} and @kbd{C-q}, so you can in effect type them as @kbd{C-\} +and @kbd{C-^} even when they are input for other commands. +@xref{Translating Input}. + +If the terminal is the source of the flow control characters, then once +you enable kernel flow control handling, you probably can make do with +less padding than normal for that terminal. You can reduce the amount +of padding by customizing the Termcap entry. You can also reduce it by +setting @code{baud-rate} to a smaller value so that Emacs uses a smaller +speed when calculating the padding needed. @xref{Terminal Output}. + +@node Batch Mode +@section Batch Mode +@cindex batch mode +@cindex noninteractive use + + The command line option @samp{-batch} causes Emacs to run +noninteractively. In this mode, Emacs does not read commands from the +terminal, it does not alter the terminal modes, and it does not expect +to be outputting to an erasable screen. The idea is that you specify +Lisp programs to run; when they are finished, Emacs should exit. The +way to specify the programs to run is with @samp{-l @var{file}}, which +loads the library named @var{file}, and @samp{-f @var{function}}, which +calls @var{function} with no arguments. + + Any Lisp program output that would normally go to the echo area, +either using @code{message} or using @code{prin1}, etc., with @code{t} +as the stream, goes instead to Emacs's standard output descriptor when +in batch mode. Thus, Emacs behaves much like a noninteractive +application program. (The echo area output that Emacs itself normally +generates, such as command echoing, is suppressed entirely.) + +@defvar noninteractive +This variable is non-@code{nil} when Emacs is running in batch mode. +@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 @@ +@c -*-texinfo-*- +@c This is part of the GNU Emacs Lisp Reference Manual. +@c Copyright (C) 1990, 1991, 1992, 1993, 1994 Free Software Foundation, Inc. +@c See the file elisp.texi for copying conditions. +@setfilename ../info/processes +@node Processes, System Interface, Abbrevs, Top +@chapter Processes +@cindex child process +@cindex parent process +@cindex subprocess +@cindex process + + In the terminology of operating systems, a @dfn{process} is a space in +which a program can execute. Emacs runs in a process. Emacs Lisp +programs can invoke other programs in processes of their own. These are +called @dfn{subprocesses} or @dfn{child processes} of the Emacs process, +which is their @dfn{parent process}. + + A subprocess of Emacs may be @dfn{synchronous} or @dfn{asynchronous}, +depending on how it is created. When you create a synchronous +subprocess, the Lisp program waits for the subprocess to terminate +before continuing execution. When you create an asynchronous +subprocess, it can run in parallel with the Lisp program. This kind of +subprocess is represented within Emacs by a Lisp object which is also +called a ``process''. Lisp programs can use this object to communicate +with the subprocess or to control it. For example, you can send +signals, obtain status information, receive output from the process, or +send input to it. + +@defun processp object +This function returns @code{t} if @var{object} is a process, +@code{nil} otherwise. +@end defun + +@menu +* Subprocess Creation:: Functions that start subprocesses. +* Synchronous Processes:: Details of using synchronous subprocesses. +* Asynchronous Processes:: Starting up an asynchronous subprocess. +* Deleting Processes:: Eliminating an asynchronous subprocess. +* Process Information:: Accessing run-status and other attributes. +* Input to Processes:: Sending input to an asynchronous subprocess. +* Signals to Processes:: Stopping, continuing or interrupting + an asynchronous subprocess. +* Output from Processes:: Collecting output from an asynchronous subprocess. +* Sentinels:: Sentinels run when process run-status changes. +* Transaction Queues:: Transaction-based communication with subprocesses. +* TCP:: Opening network connections. +@end menu + +@node Subprocess Creation +@section Functions that Create Subprocesses + + There are three functions that create a new subprocess in which to run +a program. One of them, @code{start-process}, creates an asynchronous +process and returns a process object (@pxref{Asynchronous Processes}). +The other two, @code{call-process} and @code{call-process-region}, +create a synchronous process and do not return a process object +(@pxref{Synchronous Processes}). + + Synchronous and asynchronous processes are explained in following +sections. Since the three functions are all called in a similar +fashion, their common arguments are described here. + +@cindex execute program +@cindex @code{PATH} environment variable +@cindex @code{HOME} environment variable + In all cases, the function's @var{program} argument specifies the +program to be run. An error is signaled if the file is not found or +cannot be executed. If the file name is relative, the variable +@code{exec-path} contains a list of directories to search. Emacs +initializes @code{exec-path} when it starts up, based on the value of +the environment variable @code{PATH}. The standard file name +constructs, @samp{~}, @samp{.}, and @samp{..}, are interpreted as usual +in @code{exec-path}, but environment variable substitutions +(@samp{$HOME}, etc.) are not recognized; use +@code{substitute-in-file-name} to perform them (@pxref{File Name +Expansion}). + + Each of the subprocess-creating functions has a @var{buffer-or-name} +argument which specifies where the standard output from the program will +go. If @var{buffer-or-name} is @code{nil}, that says to discard the +output unless a filter function handles it. (@xref{Filter Functions}, +and @ref{Streams}.) Normally, you should avoid having multiple +processes send output to the same buffer because their output would be +intermixed randomly. + +@cindex program arguments + All three of the subprocess-creating functions have a @code{&rest} +argument, @var{args}. The @var{args} must all be strings, and they are +supplied to @var{program} as separate command line arguments. Wildcard +characters and other shell constructs are not allowed in these strings, +since they are passed directly to the specified program. + + @strong{Please note:} the argument @var{program} contains only the +name of the program; it may not contain any command-line arguments. You +must use @var{args} to provide those. + + The subprocess gets its current directory from the value of +@code{default-directory} (@pxref{File Name Expansion}). + +@cindex environment variables, subprocesses + The subprocess inherits its environment from Emacs; but you can +specify overrides for it with @code{process-environment}. @xref{System +Environment}. + +@defvar exec-directory +@pindex wakeup +The value of this variable is the name of a directory (a string) that +contains programs that come with GNU Emacs, that are intended for Emacs +to invoke. The program @code{wakeup} is an example of such a program; +the @code{display-time} command uses it to get a reminder once per +minute. +@end defvar + +@defopt exec-path +The value of this variable is a list of directories to search for +programs to run in subprocesses. Each element is either the name of a +directory (i.e., a string), or @code{nil}, which stands for the default +directory (which is the value of @code{default-directory}). +@cindex program directories + +The value of @code{exec-path} is used by @code{call-process} and +@code{start-process} when the @var{program} argument is not an absolute +file name. +@end defopt + +@node Synchronous Processes +@section Creating a Synchronous Process +@cindex synchronous subprocess + + After a @dfn{synchronous process} is created, Emacs waits for the +process to terminate before continuing. Starting Dired is an example of +this: it runs @code{ls} in a synchronous process, then modifies the +output slightly. Because the process is synchronous, the entire +directory listing arrives in the buffer before Emacs tries to do +anything with it. + + While Emacs waits for the synchronous subprocess to terminate, the +user can quit by typing @kbd{C-g}. The first @kbd{C-g} tries to kill +the subprocess with a @code{SIGINT} signal; but it waits until the +subprocess actually terminates before quitting. If during that time the +user types another @kbd{C-g}, that kills the subprocess instantly with +@code{SIGKILL} and quits immediately. @xref{Quitting}. + + The synchronous subprocess functions returned @code{nil} in version +18. In version 19, they return an indication of how the process +terminated. + +@defun call-process program &optional infile buffer-or-name display &rest args +This function calls @var{program} in a separate process and waits for +it to finish. + +The standard input for the process comes from file @var{infile} if +@var{infile} is not @code{nil} and from @file{/dev/null} otherwise. The +process output gets inserted in buffer @var{buffer-or-name} before point, +if that argument names a buffer. If @var{buffer-or-name} is @code{t}, +output is sent to the current buffer; if @var{buffer-or-name} is +@code{nil}, output is discarded. + +If @var{buffer-or-name} is the integer 0, @code{call-process} returns +@code{nil} immediately and discards any output. In this case, the +process is not truly synchronous, since it can run in parallel with +Emacs; but you can think of it as synchronous in that Emacs is +essentially finished with the subprocess as soon as this function +returns. + +If @var{display} is non-@code{nil}, then @code{call-process} redisplays +the buffer as output is inserted. Otherwise the function does no +redisplay, and the results become visible on the screen only when Emacs +redisplays that buffer in the normal course of events. + +The remaining arguments, @var{args}, are strings that specify command +line arguments for the program. + +The value returned by @code{call-process} (unless you told it not to +wait) indicates the reason for process termination. A number gives the +exit status of the subprocess; 0 means success, and any other value +means failure. If the process terminated with a signal, +@code{call-process} returns a string describing the signal. + +In the examples below, the buffer @samp{foo} is current. + +@smallexample +@group +(call-process "pwd" nil t) + @result{} nil + +---------- Buffer: foo ---------- +/usr/user/lewis/manual +---------- Buffer: foo ---------- +@end group + +@group +(call-process "grep" nil "bar" nil "lewis" "/etc/passwd") + @result{} nil + +---------- Buffer: bar ---------- +lewis:5LTsHm66CSWKg:398:21:Bil Lewis:/user/lewis:/bin/csh + +---------- Buffer: bar ---------- +@end group +@end smallexample + +The @code{insert-directory} function contains a good example of the use +of @code{call-process}: + +@smallexample +@group +(call-process insert-directory-program nil t nil switches + (if full-directory-p + (concat (file-name-as-directory file) ".") + file)) +@end group +@end smallexample +@end defun + +@defun call-process-region start end program &optional delete buffer-or-name display &rest args +This function sends the text between @var{start} to @var{end} as +standard input to a process running @var{program}. It deletes the text +sent if @var{delete} is non-@code{nil}; this is useful when @var{buffer} +is @code{t}, to insert the output in the current buffer. + +The arguments @var{buffer-or-name} and @var{display} control what to do +with the output from the subprocess, and whether to update the display +as it comes in. For details, see the description of +@code{call-process}, above. If @var{buffer-or-name} is the integer 0, +@code{call-process-region} discards the output and returns @code{nil} +immediately, without waiting for the subprocess to finish. + +The remaining arguments, @var{args}, are strings that specify command +line arguments for the program. + +The return value of @code{call-process-region} is just like that of +@code{call-process}: @code{nil} if you told it to return without +waiting; otherwise, a number or string which indicates how the +subprocess terminated. + +In the following example, we use @code{call-process-region} to run the +@code{cat} utility, with standard input being the first five characters +in buffer @samp{foo} (the word @samp{input}). @code{cat} copies its +standard input into its standard output. Since the argument +@var{buffer-or-name} is @code{t}, this output is inserted in the current +buffer. + +@smallexample +@group +---------- Buffer: foo ---------- +input@point{} +---------- Buffer: foo ---------- +@end group + +@group +(call-process-region 1 6 "cat" nil t) + @result{} nil + +---------- Buffer: foo ---------- +inputinput@point{} +---------- Buffer: foo ---------- +@end group +@end smallexample + + The @code{shell-command-on-region} command uses +@code{call-process-region} like this: + +@smallexample +@group +(call-process-region + start end + shell-file-name ; @r{Name of program.} + nil ; @r{Do not delete region.} + buffer ; @r{Send output to @code{buffer}.} + nil ; @r{No redisplay during output.} + "-c" command) ; @r{Arguments for the shell.} +@end group +@end smallexample +@end defun + +@node Asynchronous Processes +@section Creating an Asynchronous Process +@cindex asynchronous subprocess + + After an @dfn{asynchronous process} is created, Emacs and the Lisp +program both continue running immediately. The process may thereafter +run in parallel with Emacs, and the two may communicate with each other +using the functions described in following sections. Here we describe +how to create an asynchronous process with @code{start-process}. + +@defun start-process name buffer-or-name program &rest args +This function creates a new asynchronous subprocess and starts the +program @var{program} running in it. It returns a process object that +stands for the new subprocess in Lisp. The argument @var{name} +specifies the name for the process object; if a process with this name +already exists, then @var{name} is modified (by adding @samp{<1>}, etc.) +to be unique. The buffer @var{buffer-or-name} is the buffer to +associate with the process. + +The remaining arguments, @var{args}, are strings that specify command +line arguments for the program. + +In the example below, the first process is started and runs (rather, +sleeps) for 100 seconds. Meanwhile, the second process is started, and +given the name @samp{my-process<1>} for the sake of uniqueness. It +inserts the directory listing at the end of the buffer @samp{foo}, +before the first process finishes. Then it finishes, and a message to +that effect is inserted in the buffer. Much later, the first process +finishes, and another message is inserted in the buffer for it. + +@smallexample +@group +(start-process "my-process" "foo" "sleep" "100") + @result{} #<process my-process> +@end group + +@group +(start-process "my-process" "foo" "ls" "-l" "/user/lewis/bin") + @result{} #<process my-process<1>> + +---------- Buffer: foo ---------- +total 2 +lrwxrwxrwx 1 lewis 14 Jul 22 10:12 gnuemacs --> /emacs +-rwxrwxrwx 1 lewis 19 Jul 30 21:02 lemon + +Process my-process<1> finished + +Process my-process finished +---------- Buffer: foo ---------- +@end group +@end smallexample +@end defun + +@defun start-process-shell-command name buffer-or-name command &rest command-args +This function is like @code{start-process} except that it uses a shell +to execute the specified command. The argument @var{command} is a shell +command name, and @var{command-args} are the arguments for the shell +command. +@end defun + +@defvar process-connection-type +@cindex pipes +@cindex @sc{pty}s +This variable controls the type of device used to communicate with +asynchronous subprocesses. If it is @code{nil}, then pipes are used. +If it is @code{t}, then @sc{pty}s are used (or pipes if @sc{pty}s are +not supported). + +@sc{pty}s are usually preferable for processes visible to the user, as +in Shell mode, because they allow job control (@kbd{C-c}, @kbd{C-z}, +etc.) to work between the process and its children whereas pipes do not. +For subprocesses used for internal purposes by programs, it is often +better to use a pipe, because they are more efficient. In addition, the +total number of @sc{pty}s is limited on many systems and it is good not +to waste them. + +The value @code{process-connection-type} is used when +@code{start-process} is called. So you can specify how to communicate +with one subprocess by binding the variable around the call to +@code{start-process}. + +@smallexample +@group +(let ((process-connection-type nil)) ; @r{Use a pipe.} + (start-process @dots{})) +@end group +@end smallexample +@end defvar + +@node Deleting Processes +@section Deleting Processes +@cindex deleting processes + + @dfn{Deleting a process} disconnects Emacs immediately from the +subprocess, and removes it from the list of active processes. It sends +a signal to the subprocess to make the subprocess terminate, but this is +not guaranteed to happen immediately. The process object itself +continues to exist as long as other Lisp objects point to it. + + You can delete a process explicitly at any time. Processes are +deleted automatically after they terminate, but not necessarily right +away. If you delete a terminated process explicitly before it is +deleted automatically, no harm results. + +@defvar delete-exited-processes +This variable controls automatic deletion of processes that have +terminated (due to calling @code{exit} or to a signal). If it is +@code{nil}, then they continue to exist until the user runs +@code{list-processes}. Otherwise, they are deleted immediately after +they exit. +@end defvar + +@defun delete-process name +This function deletes the process associated with @var{name}, killing it +with a @code{SIGHUP} signal. The argument @var{name} may be a process, +the name of a process, a buffer, or the name of a buffer. + +@smallexample +@group +(delete-process "*shell*") + @result{} nil +@end group +@end smallexample +@end defun + +@defun process-kill-without-query process +This function declares that Emacs need not query the user if +@var{process} is still running when Emacs is exited. The process will +be deleted silently. The value is @code{t}. + +@smallexample +@group +(process-kill-without-query (get-process "shell")) + @result{} t +@end group +@end smallexample +@end defun + +@node Process Information +@section Process Information + + Several functions return information about processes. +@code{list-processes} is provided for interactive use. + +@deffn Command list-processes +This command displays a listing of all living processes. In addition, +it finally deletes any process whose status was @samp{Exited} or +@samp{Signaled}. It returns @code{nil}. +@end deffn + +@defun process-list +This function returns a list of all processes that have not been deleted. + +@smallexample +@group +(process-list) + @result{} (#<process display-time> #<process shell>) +@end group +@end smallexample +@end defun + +@defun get-process name +This function returns the process named @var{name}, or @code{nil} if +there is none. An error is signaled if @var{name} is not a string. + +@smallexample +@group +(get-process "shell") + @result{} #<process shell> +@end group +@end smallexample +@end defun + +@defun process-command process +This function returns the command that was executed to start +@var{process}. This is a list of strings, the first string being the +program executed and the rest of the strings being the arguments that +were given to the program. + +@smallexample +@group +(process-command (get-process "shell")) + @result{} ("/bin/csh" "-i") +@end group +@end smallexample +@end defun + +@defun process-id process +This function returns the @sc{pid} of @var{process}. This is an +integer which distinguishes the process @var{process} from all other +processes running on the same computer at the current time. The +@sc{pid} of a process is chosen by the operating system kernel when the +process is started and remains constant as long as the process exists. +@end defun + +@defun process-name process +This function returns the name of @var{process}. +@end defun + +@defun process-status process-name +This function returns the status of @var{process-name} as a symbol. +The argument @var{process-name} must be a process, a buffer, a +process name (string) or a buffer name (string). + +The possible values for an actual subprocess are: + +@table @code +@item run +for a process that is running. +@item stop +for a process that is stopped but continuable. +@item exit +for a process that has exited. +@item signal +for a process that has received a fatal signal. +@item open +for a network connection that is open. +@item closed +for a network connection that is closed. Once a connection +is closed, you cannot reopen it, though you might be able to open +a new connection to the same place. +@item nil +if @var{process-name} is not the name of an existing process. +@end table + +@smallexample +@group +(process-status "shell") + @result{} run +@end group +@group +(process-status (get-buffer "*shell*")) + @result{} run +@end group +@group +x + @result{} #<process xx<1>> +(process-status x) + @result{} exit +@end group +@end smallexample + +For a network connection, @code{process-status} returns one of the symbols +@code{open} or @code{closed}. The latter means that the other side +closed the connection, or Emacs did @code{delete-process}. + +In earlier Emacs versions (prior to version 19), the status of a network +connection was @code{run} if open, and @code{exit} if closed. +@end defun + +@defun process-exit-status process +This function returns the exit status of @var{process} or the signal +number that killed it. (Use the result of @code{process-status} to +determine which of those it is.) If @var{process} has not yet +terminated, the value is 0. +@end defun + +@node Input to Processes +@section Sending Input to Processes +@cindex process input + + Asynchronous subprocesses receive input when it is sent to them by +Emacs, which is done with the functions in this section. You must +specify the process to send input to, and the input data to send. The +data appears on the ``standard input'' of the subprocess. + + Some operating systems have limited space for buffered input in a +@sc{pty}. On these systems, Emacs sends an @sc{eof} periodically amidst +the other characters, to force them through. For most programs, +these @sc{eof}s do no harm. + +@defun process-send-string process-name string +This function sends @var{process-name} the contents of @var{string} as +standard input. The argument @var{process-name} must be a process or +the name of a process. If it is @code{nil}, the current buffer's +process is used. + + The function returns @code{nil}. + +@smallexample +@group +(process-send-string "shell<1>" "ls\n") + @result{} nil +@end group + + +@group +---------- Buffer: *shell* ---------- +... +introduction.texi syntax-tables.texi~ +introduction.texi~ text.texi +introduction.txt text.texi~ +... +---------- Buffer: *shell* ---------- +@end group +@end smallexample +@end defun + +@deffn Command process-send-region process-name start end +This function sends the text in the region defined by @var{start} and +@var{end} as standard input to @var{process-name}, which is a process or +a process name. (If it is @code{nil}, the current buffer's process is +used.) + +An error is signaled unless both @var{start} and @var{end} are +integers or markers that indicate positions in the current buffer. (It +is unimportant which number is larger.) +@end deffn + +@defun process-send-eof &optional process-name + This function makes @var{process-name} see an end-of-file in its +input. The @sc{eof} comes after any text already sent to it. + + If @var{process-name} is not supplied, or if it is @code{nil}, then +this function sends the @sc{eof} to the current buffer's process. An +error is signaled if the current buffer has no process. + + The function returns @var{process-name}. + +@smallexample +@group +(process-send-eof "shell") + @result{} "shell" +@end group +@end smallexample +@end defun + +@node Signals to Processes +@section Sending Signals to Processes +@cindex process signals +@cindex sending signals +@cindex signals + + @dfn{Sending a signal} to a subprocess is a way of interrupting its +activities. There are several different signals, each with its own +meaning. The set of signals and their names is defined by the operating +system. For example, the signal @code{SIGINT} means that the user has +typed @kbd{C-c}, or that some analogous thing has happened. + + Each signal has a standard effect on the subprocess. Most signals +kill the subprocess, but some stop or resume execution instead. Most +signals can optionally be handled by programs; if the program handles +the signal, then we can say nothing in general about its effects. + + You can send signals explicitly by calling the functions in this +section. Emacs also sends signals automatically at certain times: +killing a buffer sends a @code{SIGHUP} signal to all its associated +processes; killing Emacs sends a @code{SIGHUP} signal to all remaining +processes. (@code{SIGHUP} is a signal that usually indicates that the +user hung up the phone.) + + Each of the signal-sending functions takes two optional arguments: +@var{process-name} and @var{current-group}. + + The argument @var{process-name} must be either a process, the name of +one, or @code{nil}. If it is @code{nil}, the process defaults to the +process associated with the current buffer. An error is signaled if +@var{process-name} does not identify a process. + + The argument @var{current-group} is a flag that makes a difference +when you are running a job-control shell as an Emacs subprocess. If it +is non-@code{nil}, then the signal is sent to the current process-group +of the terminal which Emacs uses to communicate with the subprocess. If +the process is a job-control shell, this means the shell's current +subjob. If it is @code{nil}, the signal is sent to the process group of +the immediate subprocess of Emacs. If the subprocess is a job-control +shell, this is the shell itself. + + The flag @var{current-group} has no effect when a pipe is used to +communicate with the subprocess, because the operating system does not +support the distinction in the case of pipes. For the same reason, +job-control shells won't work when a pipe is used. See +@code{process-connection-type} in @ref{Asynchronous Processes}. + +@defun interrupt-process &optional process-name current-group +This function interrupts the process @var{process-name} by sending the +signal @code{SIGINT}. Outside of Emacs, typing the ``interrupt +character'' (normally @kbd{C-c} on some systems, and @code{DEL} on +others) sends this signal. When the argument @var{current-group} is +non-@code{nil}, you can think of this function as ``typing @kbd{C-c}'' +on the terminal by which Emacs talks to the subprocess. +@end defun + +@defun kill-process &optional process-name current-group +This function kills the process @var{process-name} by sending the +signal @code{SIGKILL}. This signal kills the subprocess immediately, +and cannot be handled by the subprocess. +@end defun + +@defun quit-process &optional process-name current-group +This function sends the signal @code{SIGQUIT} to the process +@var{process-name}. This signal is the one sent by the ``quit +character'' (usually @kbd{C-b} or @kbd{C-\}) when you are not inside +Emacs. +@end defun + +@defun stop-process &optional process-name current-group +This function stops the process @var{process-name} by sending the +signal @code{SIGTSTP}. Use @code{continue-process} to resume its +execution. + +On systems with job control, the ``stop character'' (usually @kbd{C-z}) +sends this signal (outside of Emacs). When @var{current-group} is +non-@code{nil}, you can think of this function as ``typing @kbd{C-z}'' +on the terminal Emacs uses to communicate with the subprocess. +@end defun + +@defun continue-process &optional process-name current-group +This function resumes execution of the process @var{process} by sending +it the signal @code{SIGCONT}. This presumes that @var{process-name} was +stopped previously. +@end defun + +@c Emacs 19 feature +@defun signal-process pid signal +This function sends a signal to process @var{pid}, which need not be +a child of Emacs. The argument @var{signal} specifies which signal +to send; it should be an integer. +@end defun + +@node Output from Processes +@section Receiving Output from Processes +@cindex process output +@cindex output from processes + + There are two ways to receive the output that a subprocess writes to +its standard output stream. The output can be inserted in a buffer, +which is called the associated buffer of the process, or a function +called the @dfn{filter function} can be called to act on the output. + +@menu +* Process Buffers:: If no filter, output is put in a buffer. +* Filter Functions:: Filter functions accept output from the process. +* Accepting Output:: Explicitly permitting subprocess output. + Waiting for subprocess output. +@end menu + +@node Process Buffers +@subsection Process Buffers + + A process can (and usually does) have an @dfn{associated buffer}, +which is an ordinary Emacs buffer that is used for two purposes: storing +the output from the process, and deciding when to kill the process. You +can also use the buffer to identify a process to operate on, since in +normal practice only one process is associated with any given buffer. +Many applications of processes also use the buffer for editing input to +be sent to the process, but this is not built into Emacs Lisp. + + Unless the process has a filter function (@pxref{Filter Functions}), +its output is inserted in the associated buffer. The position to insert +the output is determined by the @code{process-mark} (@pxref{Process +Information}), which is then updated to point to the end of the text +just inserted. Usually, but not always, the @code{process-mark} is at +the end of the buffer. If the process has no buffer and no filter +function, its output is discarded. + +@defun process-buffer process +This function returns the associated buffer of the process +@var{process}. + +@smallexample +@group +(process-buffer (get-process "shell")) + @result{} #<buffer *shell*> +@end group +@end smallexample +@end defun + +@defun process-mark process +This function returns the process marker for @var{process}, which is the +marker that says where to insert output from the process. + +If @var{process} does not have a buffer, @code{process-mark} returns a +marker that points nowhere. + +Insertion of process output in a buffer uses this marker to decide where +to insert, and updates it to point after the inserted text. That is why +successive batches of output are inserted consecutively. + +Filter functions normally should use this marker in the same fashion +as is done by direct insertion of output in the buffer. A good +example of a filter function that uses @code{process-mark} is found at +the end of the following section. + +When the user is expected to enter input in the process buffer for +transmission to the process, the process marker is useful for +distinguishing the new input from previous output. +@end defun + +@defun set-process-buffer process buffer +This function sets the buffer associated with @var{process} to +@var{buffer}. If @var{buffer} is @code{nil}, the process becomes +associated with no buffer. +@end defun + +@defun get-buffer-process buffer-or-name +This function returns the process associated with @var{buffer-or-name}. +If there are several processes associated with it, then one is chosen. +(Presently, the one chosen is the one most recently created.) It is +usually a bad idea to have more than one process associated with the +same buffer. + +@smallexample +@group +(get-buffer-process "*shell*") + @result{} #<process shell> +@end group +@end smallexample + +Killing the process's buffer deletes the process, which kills the +subprocess with a @code{SIGHUP} signal (@pxref{Signals to Processes}). +@end defun + +@node Filter Functions +@subsection Process Filter Functions +@cindex filter function +@cindex process filter + + A process @dfn{filter function} is a function that receives the +standard output from the associated process. If a process has a filter, +then @emph{all} output from that process, that would otherwise have been +in a buffer, is passed to the filter. The process buffer is used +directly for output from the process only when there is no filter. + + A filter function must accept two arguments: the associated process and +a string, which is the output. The function is then free to do whatever it +chooses with the output. + + A filter function runs only while Emacs is waiting (e.g., for terminal +input, or for time to elapse, or for process output). This avoids the +timing errors that could result from running filters at random places in +the middle of other Lisp programs. You may explicitly cause Emacs to +wait, so that filter functions will run, by calling @code{sit-for}, +@code{sleep-for} or @code{accept-process-output} (@pxref{Accepting +Output}). Emacs is also waiting when the command loop is reading input. + + Quitting is normally inhibited within a filter function---otherwise, +the effect of typing @kbd{C-g} at command level or to quit a user +command would be unpredictable. If you want to permit quitting inside a +filter function, bind @code{inhibit-quit} to @code{nil}. +@xref{Quitting}. + + Many filter functions sometimes or always insert the text in the +process's buffer, mimicking the actions of Emacs when there is no +filter. Such filter functions need to use @code{set-buffer} in order to +be sure to insert in that buffer. To avoid setting the current buffer +semipermanently, these filter functions must use @code{unwind-protect} +to make sure to restore the previous current buffer. They should also +update the process marker, and in some cases update the value of point. +Here is how to do these things: + +@smallexample +@group +(defun ordinary-insertion-filter (proc string) + (let ((old-buffer (current-buffer))) + (unwind-protect + (let (moving) + (set-buffer (process-buffer proc)) + (setq moving (= (point) (process-mark proc))) +@end group +@group + (save-excursion + ;; @r{Insert the text, moving the process-marker.} + (goto-char (process-mark proc)) + (insert string) + (set-marker (process-mark proc) (point))) + (if moving (goto-char (process-mark proc)))) + (set-buffer old-buffer)))) +@end group +@end smallexample + +@noindent +The reason to use an explicit @code{unwind-protect} rather than letting +@code{save-excursion} restore the current buffer is so as to preserve +the change in point made by @code{goto-char}. + + To make the filter force the process buffer to be visible whenever new +text arrives, insert the following line just before the +@code{unwind-protect}: + +@smallexample +(display-buffer (process-buffer proc)) +@end smallexample + + To force point to move to the end of the new output no matter where +it was previously, eliminate the variable @code{moving} and call +@code{goto-char} unconditionally. + + All filter functions that do regexp searching or matching should save +and restore the match data. Otherwise, a filter function that runs +during a call to @code{sit-for} might clobber the match data of the +program that called @code{sit-for}. @xref{Match Data}. + + A filter function that writes the output into the buffer of the +process should check whether the process is still alive. If it tries to +insert into a dead buffer, it will get an error. If the buffer is dead, +@code{(buffer-name (process-buffer @var{process}))} returns @code{nil}. + + The output to the function may come in chunks of any size. A program +that produces the same output twice in a row may send it as one batch +of 200 characters one time, and five batches of 40 characters the next. + +@defun set-process-filter process filter +This function gives @var{process} the filter function @var{filter}. If +@var{filter} is @code{nil}, it gives the process no filter. +@end defun + +@defun process-filter process +This function returns the filter function of @var{process}, or @code{nil} +if it has none. +@end defun + + Here is an example of use of a filter function: + +@smallexample +@group +(defun keep-output (process output) + (setq kept (cons output kept))) + @result{} keep-output +@end group +@group +(setq kept nil) + @result{} nil +@end group +@group +(set-process-filter (get-process "shell") 'keep-output) + @result{} keep-output +@end group +@group +(process-send-string "shell" "ls ~/other\n") + @result{} nil +kept + @result{} ("lewis@@slug[8] % " +@end group +@group +"FINAL-W87-SHORT.MSS backup.otl kolstad.mss~ +address.txt backup.psf kolstad.psf +backup.bib~ david.mss resume-Dec-86.mss~ +backup.err david.psf resume-Dec.psf +backup.mss dland syllabus.mss +" +"#backups.mss# backup.mss~ kolstad.mss +") +@end group +@end smallexample + +@ignore @c The code in this example doesn't show the right way to do things. +Here is another, more realistic example, which demonstrates how to use +the process mark to do insertion in the same fashion as is done when +there is no filter function: + +@smallexample +@group +;; @r{Insert input in the buffer specified by @code{my-shell-buffer}} +;; @r{and make sure that buffer is shown in some window.} +(defun my-process-filter (proc str) + (let ((cur (selected-window)) + (pop-up-windows t)) + (pop-to-buffer my-shell-buffer) +@end group +@group + (goto-char (point-max)) + (insert str) + (set-marker (process-mark proc) (point-max)) + (select-window cur))) +@end group +@end smallexample +@end ignore + +@node Accepting Output +@subsection Accepting Output from Processes + + Output from asynchronous subprocesses normally arrives only while +Emacs is waiting for some sort of external event, such as elapsed time +or terminal input. Occasionally it is useful in a Lisp program to +explicitly permit output to arrive at a specific point, or even to wait +until output arrives from a process. + +@defun accept-process-output &optional process seconds millisec +This function allows Emacs to read pending output from processes. The +output is inserted in the associated buffers or given to their filter +functions. If @var{process} is non-@code{nil} then this function does +not return until some output has been received from @var{process}. + +@c Emacs 19 feature +The arguments @var{seconds} and @var{millisec} let you specify timeout +periods. The former specifies a period measured in seconds and the +latter specifies one measured in milliseconds. The two time periods +thus specified are added together, and @code{accept-process-output} +returns after that much time whether or not there has been any +subprocess output. + +Not all operating systems support waiting periods other than multiples +of a second; on those that do not, you get an error if you specify +nonzero @var{millisec}. + +The function @code{accept-process-output} returns non-@code{nil} if it +did get some output, or @code{nil} if the timeout expired before output +arrived. +@end defun + +@node Sentinels +@section Sentinels: Detecting Process Status Changes +@cindex process sentinel +@cindex sentinel + + A @dfn{process sentinel} is a function that is called whenever the +associated process changes status for any reason, including signals +(whether sent by Emacs or caused by the process's own actions) that +terminate, stop, or continue the process. The process sentinel is also +called if the process exits. The sentinel receives two arguments: the +process for which the event occurred, and a string describing the type +of event. + + The string describing the event looks like one of the following: + +@itemize @bullet +@item +@code{"finished\n"}. + +@item +@code{"exited abnormally with code @var{exitcode}\n"}. + +@item +@code{"@var{name-of-signal}\n"}. + +@item +@code{"@var{name-of-signal} (core dumped)\n"}. +@end itemize + + A sentinel runs only while Emacs is waiting (e.g., for terminal input, +or for time to elapse, or for process output). This avoids the timing +errors that could result from running them at random places in the +middle of other Lisp programs. A program can wait, so that sentinels +will run, by calling @code{sit-for}, @code{sleep-for} or +@code{accept-process-output} (@pxref{Accepting Output}). Emacs is also +waiting when the command loop is reading input. + + Quitting is normally inhibited within a sentinel---otherwise, the +effect of typing @kbd{C-g} at command level or to quit a user command +would be unpredictable. If you want to permit quitting inside a +sentinel, bind @code{inhibit-quit} to @code{nil}. @xref{Quitting}. + + A sentinel that writes the output into the buffer of the process +should check whether the process is still alive. If it tries to insert +into a dead buffer, it will get an error. If the buffer is dead, +@code{(buffer-name (process-buffer @var{process}))} returns @code{nil}. + + All sentinels that do regexp searching or matching should save and +restore the match data. Otherwise, a sentinel that runs during a call +to @code{sit-for} might clobber the match data of the program that +called @code{sit-for}. @xref{Match Data}. + +@defun set-process-sentinel process sentinel +This function associates @var{sentinel} with @var{process}. If +@var{sentinel} is @code{nil}, then the process will have no sentinel. +The default behavior when there is no sentinel is to insert a message in +the process's buffer when the process status changes. + +@smallexample +@group +(defun msg-me (process event) + (princ + (format "Process: %s had the event `%s'" process event))) +(set-process-sentinel (get-process "shell") 'msg-me) + @result{} msg-me +@end group +@group +(kill-process (get-process "shell")) + @print{} Process: #<process shell> had the event `killed' + @result{} #<process shell> +@end group +@end smallexample +@end defun + +@defun process-sentinel process +This function returns the sentinel of @var{process}, or @code{nil} if it +has none. +@end defun + +@defun waiting-for-user-input-p +While a sentinel or filter function is running, this function returns +non-@code{nil} if Emacs was waiting for keyboard input from the user at +the time the sentinel or filter function was called, @code{nil} if it +was not. +@end defun + +@node Transaction Queues +@section Transaction Queues +@cindex transaction queue + +You can use a @dfn{transaction queue} for more convenient communication +with subprocesses using transactions. First use @code{tq-create} to +create a transaction queue communicating with a specified process. Then +you can call @code{tq-enqueue} to send a transaction. + +@defun tq-create process +This function creates and returns a transaction queue communicating with +@var{process}. The argument @var{process} should be a subprocess +capable of sending and receiving streams of bytes. It may be a child +process, or it may be a TCP connection to a server possibly on another +machine. +@end defun + +@defun tq-enqueue queue question regexp closure fn +This function sends a transaction to queue @var{queue}. Specifying the +queue has the effect of specifying the subprocess to talk to. + +The argument @var{question} is the outgoing message which starts the +transaction. The argument @var{fn} is the function to call when the +corresponding answer comes back; it is called with two arguments: +@var{closure}, and the answer received. + +The argument @var{regexp} is a regular expression that should match the +entire answer, but nothing less; that's how @code{tq-enqueue} determines +where the answer ends. + +The return value of @code{tq-enqueue} itself is not meaningful. +@end defun + +@defun tq-close queue +Shut down transaction queue @var{queue}, waiting for all pending transactions +to complete, and then terminate the connection or child process. +@end defun + +Transaction queues are implemented by means of a filter function. +@xref{Filter Functions}. + +@node TCP +@section TCP +@cindex TCP + + Emacs Lisp programs can open TCP connections to other processes on the +same machine or other machines. A network connection is handled by Lisp +much like a subprocess, and is represented by a process object. +However, the process you are communicating with is not a child of the +Emacs process, so you can't kill it or send it signals. All you can do +is send and receive data. @code{delete-process} closes the connection, +but does not kill the process at the other end; that process must decide +what to do about closure of the connection. + + You can distinguish process objects representing network connections +from those representing subprocesses with the @code{process-status} +function. @xref{Process Information}. + +@defun open-network-stream name buffer-or-name host service +This function opens a TCP connection for a service to a host. It +returns a process object to represent the connection. + +The @var{name} argument specifies the name for the process object. It +is modified as necessary to make it unique. + +The @var{buffer-or-name} argument is the buffer to associate with the +connection. Output from the connection is inserted in the buffer, +unless you specify a filter function to handle the output. If +@var{buffer-or-name} is @code{nil}, it means that the connection is not +associated with any buffer. + +The arguments @var{host} and @var{service} specify where to connect to; +@var{host} is the host name (a string), and @var{service} is the name of +a defined network service (a string) or a port number (an integer). +@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 @@ +@c -*-texinfo-*- +@c This is part of the GNU Emacs Lisp Reference Manual. +@c Copyright (C) 1990, 1991, 1992, 1993, 1994 Free Software Foundation, Inc. +@c See the file elisp.texi for copying conditions. +@setfilename ../info/text +@node Text, Searching and Matching, Markers, Top +@chapter Text +@cindex text + + This chapter describes the functions that deal with the text in a +buffer. Most examine, insert or delete text in the current buffer, +often in the vicinity of point. Many are interactive. All the +functions that change the text provide for undoing the changes +(@pxref{Undo}). + + Many text-related functions operate on a region of text defined by two +buffer positions passed in arguments named @var{start} and @var{end}. +These arguments should be either markers (@pxref{Markers}) or numeric +character positions (@pxref{Positions}). The order of these arguments +does not matter; it is all right for @var{start} to be the end of the +region and @var{end} the beginning. For example, @code{(delete-region 1 +10)} and @code{(delete-region 10 1)} are equivalent. An +@code{args-out-of-range} error is signaled if either @var{start} or +@var{end} is outside the accessible portion of the buffer. In an +interactive call, point and the mark are used for these arguments. + +@cindex buffer contents + Throughout this chapter, ``text'' refers to the characters in the +buffer. + +@menu +* Near Point:: Examining text in the vicinity of point. +* Buffer Contents:: Examining text in a general fashion. +* Comparing Text:: Comparing substrings of buffers. +* Insertion:: Adding new text to a buffer. +* Commands for Insertion:: User-level commands to insert text. +* Deletion:: Removing text from a buffer. +* User-Level Deletion:: User-level commands to delete text. +* The Kill Ring:: Where removed text sometimes is saved for later use. +* Undo:: Undoing changes to the text of a buffer. +* Maintaining Undo:: How to enable and disable undo information. + How to control how much information is kept. +* Filling:: Functions for explicit filling. +* Auto Filling:: How auto-fill mode is implemented to break lines. +* Sorting:: Functions for sorting parts of the buffer. +* Columns:: Computing horizontal positions, and using them. +* Indentation:: Functions to insert or adjust indentation. +* Case Changes:: Case conversion of parts of the buffer. +* Text Properties:: Assigning Lisp property lists to text characters. +* Substitution:: Replacing a given character wherever it appears. +* Registers:: How registers are implemented. Accessing the text or + position stored in a register. +* Change Hooks:: Supplying functions to be run when text is changed. +@end menu + +@node Near Point +@section Examining Text Near Point + + Many functions are provided to look at the characters around point. +Several simple functions are described here. See also @code{looking-at} +in @ref{Regexp Search}. + +@defun char-after position +This function returns the character in the current buffer at (i.e., +immediately after) position @var{position}. If @var{position} is out of +range for this purpose, either before the beginning of the buffer, or at +or beyond the end, then the value is @code{nil}. + +In the following example, assume that the first character in the +buffer is @samp{@@}: + +@example +@group +(char-to-string (char-after 1)) + @result{} "@@" +@end group +@end example +@end defun + +@defun following-char +This function returns the character following point in the current +buffer. This is similar to @code{(char-after (point))}. However, if +point is at the end of the buffer, then @code{following-char} returns 0. + +Remember that point is always between characters, and the terminal +cursor normally appears over the character following point. Therefore, +the character returned by @code{following-char} is the character the +cursor is over. + +In this example, point is between the @samp{a} and the @samp{c}. + +@example +@group +---------- Buffer: foo ---------- +Gentlemen may cry ``Pea@point{}ce! Peace!,'' +but there is no peace. +---------- Buffer: foo ---------- +@end group + +@group +(char-to-string (preceding-char)) + @result{} "a" +(char-to-string (following-char)) + @result{} "c" +@end group +@end example +@end defun + +@defun preceding-char +This function returns the character preceding point in the current +buffer. See above, under @code{following-char}, for an example. If +point is at the beginning of the buffer, @code{preceding-char} returns +0. +@end defun + +@defun bobp +This function returns @code{t} if point is at the beginning of the +buffer. If narrowing is in effect, this means the beginning of the +accessible portion of the text. See also @code{point-min} in +@ref{Point}. +@end defun + +@defun eobp +This function returns @code{t} if point is at the end of the buffer. +If narrowing is in effect, this means the end of accessible portion of +the text. See also @code{point-max} in @xref{Point}. +@end defun + +@defun bolp +This function returns @code{t} if point is at the beginning of a line. +@xref{Text Lines}. The beginning of the buffer (or its accessible +portion always counts as the beginning of a line. +@end defun + +@defun eolp +This function returns @code{t} if point is at the end of a line. The +end of the buffer (or of its accessible portion) is always considered +the end of a line. +@end defun + +@node Buffer Contents +@section Examining Buffer Contents + + This section describes two functions that allow a Lisp program to +convert any portion of the text in the buffer into a string. + +@defun buffer-substring start end +This function returns a string containing a copy of the text of the +region defined by positions @var{start} and @var{end} in the current +buffer. If the arguments are not positions in the accessible portion of +the buffer, @code{buffer-substring} signals an @code{args-out-of-range} +error. + +It is not necessary for @var{start} to be less than @var{end}; the +arguments can be given in either order. But most often the smaller +argument is written first. + +@example +@group +---------- Buffer: foo ---------- +This is the contents of buffer foo + +---------- Buffer: foo ---------- +@end group + +@group +(buffer-substring 1 10) +@result{} "This is t" +@end group +@group +(buffer-substring (point-max) 10) +@result{} "he contents of buffer foo +" +@end group +@end example +@end defun + +@defun buffer-string +This function returns the contents of the accessible portion of the +current buffer as a string. This is the portion between +@code{(point-min)} and @code{(point-max)} (@pxref{Narrowing}). + +@example +@group +---------- Buffer: foo ---------- +This is the contents of buffer foo + +---------- Buffer: foo ---------- + +(buffer-string) + @result{} "This is the contents of buffer foo +" +@end group +@end example +@end defun + +@node Comparing Text +@section Comparing Text +@cindex comparing buffer text + + This function lets you compare portions of the text in a buffer, without +copying them into strings first. + +@defun compare-buffer-substrings buffer1 start1 end1 buffer2 start2 end2 +This function lets you compare two substrings of the same buffer or two +different buffers. The first three arguments specify one substring, +giving a buffer and two positions within the buffer. The last three +arguments specify the other substring in the same way. You can use +@code{nil} for @var{buffer1}, @var{buffer2} or both to stand for the +current buffer. + +The value is negative if the first substring is less, positive if the +first is greater, and zero if they are equal. The absolute value of +the result is one plus the index of the first differing characters +within the substrings. + +This function ignores case when comparing characters +if @code{case-fold-search} is non-@code{nil}. + +Suppose the current buffer contains the text @samp{foobarbar +haha!rara!}; then in this example the two substrings are @samp{rbar } +and @samp{rara!}. The value is 2 because the first substring is greater +at the second character. + +@example +(compare-buffer-substring nil 6 11 nil 16 21) + @result{} 2 +@end example + +This function does not exist in Emacs version 18 and earlier. +@end defun + +@node Insertion +@section Insertion +@cindex insertion of text +@cindex text insertion + + @dfn{Insertion} means adding new text to a buffer. The inserted text +goes at point---between the character before point and the character +after point. + + Insertion relocates markers that point at positions after the +insertion point, so that they stay with the surrounding text +(@pxref{Markers}). When a marker points at the place of insertion, +insertion normally doesn't relocate the marker, so that it points to the +beginning of the inserted text; however, certain special functions such +as @code{insert-before-markers} relocate such markers to point after the +inserted text. + +@cindex insertion before point +@cindex before point, insertion + Some insertion functions leave point before the inserted text, while +other functions leave it after. We call the latter insertion +@dfn{before point}. + + Insertion functions signal an error if the current buffer is +read-only. + +@defun insert &rest args +This function inserts the strings and/or characters @var{args} into the +current buffer, at point, moving point forward. An error is signaled +unless all @var{args} are either strings or characters. The value is +@code{nil}. +@end defun + +@defun insert-before-markers &rest args +This function inserts the strings and/or characters @var{args} into the +current buffer, at point, moving point forward. An error is signaled +unless all @var{args} are either strings or characters. The value is +@code{nil}. + +This function is unlike the other insertion functions in that it +relocates markers initially pointing at the insertion point, to point +after the inserted text. +@end defun + +@defun insert-char character count +This function inserts @var{count} instances of @var{character} into the +current buffer before point. The argument @var{count} must be a number, +and @var{character} must be a character. The value is @code{nil}. +@c It's unfortunate that count comes second. Not like make-string, etc. +@end defun + +@defun insert-buffer-substring from-buffer-or-name &optional start end +This function inserts a portion of buffer @var{from-buffer-or-name} +(which must already exist) into the current buffer before point. The +text inserted is the region from @var{start} and @var{end}. (These +arguments default to the beginning and end of the accessible portion of +that buffer.) This function returns @code{nil}. + +In this example, the form is executed with buffer @samp{bar} as the +current buffer. We assume that buffer @samp{bar} is initially empty. + +@example +@group +---------- Buffer: foo ---------- +We hold these truths to be self-evident, that all +---------- Buffer: foo ---------- +@end group + +@group +(insert-buffer-substring "foo" 1 20) + @result{} nil + +---------- Buffer: bar ---------- +We hold these truth +---------- Buffer: bar ---------- +@end group +@end example +@end defun + + @xref{Sticky Properties}, for other insertion functions that inherit +text properties from the nearby text. + +@node Commands for Insertion +@section User-Level Insertion Commands + + This section describes higher-level commands for inserting text, +commands intended primarily for the user but useful also in Lisp +programs. + +@deffn Command insert-buffer from-buffer-or-name +This command inserts the entire contents of @var{from-buffer-or-name} +(which must exist) into the current buffer after point. It leaves +the mark after the inserted text. The value is @code{nil}. +@end deffn + +@deffn Command self-insert-command count +@cindex character insertion +@cindex self-insertion +This command inserts the last character typed @var{count} times and +returns @code{nil}. Most printing characters are bound to this command. +In routine use, @code{self-insert-command} is the most frequently called +function in Emacs, but programs rarely use it except to install it on a +keymap. + +In an interactive call, @var{count} is the numeric prefix argument. + +This function calls @code{auto-fill-function} if the current column number +is greater than the value of @code{fill-column} and the character +inserted is a space (@pxref{Auto Filling}). + +@c Cross refs reworded to prevent overfull hbox. --rjc 15mar92 +This function performs abbrev expansion if Abbrev mode is enabled and +the inserted character does not have word-constituent +syntax. (@xref{Abbrevs}, and @ref{Syntax Class Table}.) + +This function is also responsible for calling +@code{blink-paren-function} when the inserted character has close +parenthesis syntax (@pxref{Blinking}). +@end deffn + +@deffn Command newline &optional number-of-newlines +This command inserts newlines into the current buffer before point. +If @var{number-of-newlines} is supplied, that many newline characters +are inserted. + +@cindex newline and Auto Fill mode +In Auto Fill mode, @code{newline} can break the preceding line if +@var{number-of-newlines} is not supplied. When this happens, it +actually inserts two newlines at different places: one at point, and +another earlier in the line. @code{newline} does not auto-fill if +@var{number-of-newlines} is non-@code{nil}. + +The value returned is @code{nil}. In an interactive call, @var{count} +is the numeric prefix argument. +@end deffn + +@deffn Command split-line +This command splits the current line, moving the portion of the line +after point down vertically, so that it is on the next line directly +below where it was before. Whitespace is inserted as needed at the +beginning of the lower line, using the @code{indent-to} function. +@code{split-line} returns the position of point. + +Programs hardly ever use this function. +@end deffn + +@defvar overwrite-mode +This variable controls whether overwrite mode is in effect: a +non-@code{nil} value enables the mode. It is automatically made +buffer-local when set in any fashion. +@end defvar + +@node Deletion +@section Deletion of Text + +@cindex deletion vs killing + Deletion means removing part of the text in a buffer, without saving +it in the kill ring (@pxref{The Kill Ring}). Deleted text can't be +yanked, but can be reinserted using the undo mechanism (@pxref{Undo}). +Some deletion functions save text in the kill ring in some cases +but not in the usual case. + + All of the deletion functions operate on the current buffer, and all +return a value of @code{nil}. + +@defun erase-buffer +This function deletes the entire text of the current buffer, leaving it +empty. If the buffer is read-only, it signals a @code{buffer-read-only} +error. Otherwise, it deletes the text without asking for any +confirmation. It returns @code{nil}. + +Normally, deleting a large amount of text from a buffer inhibits further +auto-saving of that buffer ``because it has shrunk''. However, +@code{erase-buffer} does not do this, the idea being that the future +text is not really related to the former text, and its size should not +be compared with that of the former text. +@end defun + +@deffn Command delete-region start end +This command deletes the text in the current buffer in the region +defined by @var{start} and @var{end}. The value is @code{nil}. +@end deffn + +@deffn Command delete-char count &optional killp +This command deletes @var{count} characters directly after point, or +before point if @var{count} is negative. If @var{killp} is +non-@code{nil}, then it saves the deleted characters in the kill ring. + +In an interactive call, @var{count} is the numeric prefix argument, and +@var{killp} is the unprocessed prefix argument. Therefore, if a prefix +argument is supplied, the text is saved in the kill ring. If no prefix +argument is supplied, then one character is deleted, but not saved in +the kill ring. + +The value returned is always @code{nil}. +@end deffn + +@deffn Command delete-backward-char count &optional killp +@cindex delete previous char +This command deletes @var{count} characters directly before point, or +after point if @var{count} is negative. If @var{killp} is +non-@code{nil}, then it saves the deleted characters in the kill ring. + +In an interactive call, @var{count} is the numeric prefix argument, and +@var{killp} is the unprocessed prefix argument. Therefore, if a prefix +argument is supplied, the text is saved in the kill ring. If no prefix +argument is supplied, then one character is deleted, but not saved in +the kill ring. + +The value returned is always @code{nil}. +@end deffn + +@deffn Command backward-delete-char-untabify count &optional killp +@cindex tab deletion +This command deletes @var{count} characters backward, changing tabs +into spaces. When the next character to be deleted is a tab, it is +first replaced with the proper number of spaces to preserve alignment +and then one of those spaces is deleted instead of the tab. If +@var{killp} is non-@code{nil}, then the command saves the deleted +characters in the kill ring. + +Conversion of tabs to spaces happens only if @var{count} is positive. +If it is negative, exactly @minus{}@var{count} characters after point +are deleted. + +In an interactive call, @var{count} is the numeric prefix argument, and +@var{killp} is the unprocessed prefix argument. Therefore, if a prefix +argument is supplied, the text is saved in the kill ring. If no prefix +argument is supplied, then one character is deleted, but not saved in +the kill ring. + +The value returned is always @code{nil}. +@end deffn + +@node User-Level Deletion +@section User-Level Deletion Commands + + This section describes higher-level commands for deleting text, +commands intended primarily for the user but useful also in Lisp +programs. + +@deffn Command delete-horizontal-space +@cindex deleting whitespace +This function deletes all spaces and tabs around point. It returns +@code{nil}. + +In the following examples, we call @code{delete-horizontal-space} four +times, once on each line, with point between the second and third +characters on the successive line. + +@example +@group +---------- Buffer: foo ---------- +I @point{}thought +I @point{} thought +We@point{} thought +Yo@point{}u thought +---------- Buffer: foo ---------- +@end group + +@group +(delete-horizontal-space) ; @r{Four times.} + @result{} nil + +---------- Buffer: foo ---------- +Ithought +Ithought +Wethought +You thought +---------- Buffer: foo ---------- +@end group +@end example +@end deffn + +@deffn Command delete-indentation &optional join-following-p +This function joins the line point is on to the previous line, deleting +any whitespace at the join and in some cases replacing it with one +space. If @var{join-following-p} is non-@code{nil}, +@code{delete-indentation} joins this line to the following line +instead. The value is @code{nil}. + +If there is a fill prefix, and the second of the lines being joined +starts with the prefix, then @code{delete-indentation} deletes the +fill prefix before joining the lines. + +In the example below, point is located on the line starting +@samp{events}, and it makes no difference if there are trailing spaces +in the preceding line. + +@smallexample +---------- Buffer: foo ---------- +When in the course of human +@point{} events, it becomes necessary +---------- Buffer: foo ---------- + +(delete-indentation) + @result{} nil + +---------- Buffer: foo ---------- +When in the course of human@point{} events, it becomes necessary +---------- Buffer: foo ---------- +@end smallexample + +After the lines are joined, the function @code{fixup-whitespace} is +responsible for deciding whether to leave a space at the junction. +@end deffn + +@defun fixup-whitespace +This function replaces all the white space surrounding point with either +one space or no space, according to the context. It returns @code{nil}. + +At the beginning or end of a line, the appropriate amount of space is +none. Before a character with close parenthesis syntax, or after a +character with open parenthesis or expression-prefix syntax, no space is +also appropriate. Otherwise, one space is appropriate. @xref{Syntax +Class Table}. + +In the example below, @code{fixup-whitespace} is called the first time +with point before the word @samp{spaces} in the first line. for the +second invocation, Point is directly after the @samp{(}. + +@smallexample +@group +---------- Buffer: foo ---------- +This has too many @point{}spaces +This has too many spaces at the start of (@point{} this list) +---------- Buffer: foo ---------- +@end group + +@group +(fixup-whitespace) + @result{} nil +(fixup-whitespace) + @result{} nil +@end group + +@group +---------- Buffer: foo ---------- +This has too many spaces +This has too many spaces at the start of (this list) +---------- Buffer: foo ---------- +@end group +@end smallexample +@end defun + +@deffn Command just-one-space +@comment !!SourceFile simple.el +This command replaces any spaces and tabs around point with a single +space. It returns @code{nil}. +@end deffn + +@deffn Command delete-blank-lines +This function deletes blank lines surrounding point. If point is on a +blank line with one or more blank lines before or after it, then all but +one of them are deleted. If point is on an isolated blank line, then it +is deleted. If point is on a nonblank line, the command deletes all +blank lines following it. + +A blank line is defined as a line containing only tabs and spaces. + +@code{delete-blank-lines} returns @code{nil}. +@end deffn + +@node The Kill Ring +@section The Kill Ring +@cindex kill ring + + @dfn{Kill} functions delete text like the deletion functions, but save +it so that the user can reinsert it by @dfn{yanking}. Most of these +functions have @samp{kill-} in their name. By contrast, the functions +whose names start with @samp{delete-} normally do not save text for +yanking (though they can still be undone); these are ``deletion'' +functions. + + Most of the kill commands are primarily for interactive use, and are +not described here. What we do describe are the functions provided for +use in writing such commands. You can use these functions to write +commands for killing text. When you need to deleting text for internal +purposes within a Lisp function, you should normally use deletion +functions, so as not to disturb the kill ring contents. +@xref{Deletion}. + + Killed text is saved for later yanking in the @dfn{kill ring}. This +is a list which holds, not just the last text kill, but a number of +recent kills. We call this a ``ring'' because yanking treats it as a +cyclic order. The list is kept in the variable @code{kill-ring}, and +can be operated on with the usual functions for lists; there are also +specialized functions, described in this section, which treat it as a +ring. + + Some people think this use of the word ``kill'' is unfortunate, since +it refers to operations which specifically @emph{do not} destroy the +entities ``killed''. This is in sharp contrast to ordinary life, in +which death is permanent and ``killed'' entities do not come back to +life. Therefore, other metaphors have been proposed. For example, the +term ``cut ring'' makes sense to people who, in pre-computer days, used +scissors and paste to cut up and rearrange manuscripts. However, it +would be difficult to change the terminology now. + +@menu +* Kill Ring Concepts:: What text looks like in the kill ring. +* Kill Functions:: Functions that kill text. +* Yank Commands:: Commands that access the kill ring. +* Low Level Kill Ring:: Functions and variables for kill ring access. +* Internals of Kill Ring:: Variables that hold kill-ring data. +@end menu + +@node Kill Ring Concepts +@comment node-name, next, previous, up +@subsection Kill Ring Concepts + + The kill ring records killed text as strings in a list, most recent +first. A short kill ring, for example, might look like this: + +@example +("some text" "a different piece of text" "even older text") +@end example + +@noindent +When the list reaches @code{kill-ring-max} entries in length, adding a +new entry automatically deletes the last entry. + + When kill commands are interwoven with other commands, each kill +command makes a new entry in the kill ring. Multiple kill commands in +succession build up a single entry in the kill ring, which would be +yanked as a unit. The second and subsequent consecutive kill commands +add text to the entry made by the first one. + + For yanking, one entry in the kill ring is designated the ``front'' of +the ring. Some yank commands ``rotate'' the ring by designating a +different element as the ``front.'' But this virtual rotation doesn't +change the list itself---the most recent entry always comes first in the +list. + +@node Kill Functions +@comment node-name, next, previous, up +@subsection Functions for Killing + + @code{kill-region} is the usual subroutine for killing text. Any +command that calls this function is a ``kill command'' (and should +probably have @samp{kill} in its name). @code{kill-region} puts the +newly killed text in a new element at the beginning of the kill ring or +adds it to the most recent element. It uses the @code{last-command} +variable to determine whether the previous was a kill command, and if so +appends the killed text to the most recent entry. + +@deffn Command kill-region start end +This function kills the text in the region defined by @var{start} and +@var{end}. The text is deleted but saved in the kill ring. The value +is always @code{nil}. + +In an interactive call, @var{start} and @var{end} are point and +the mark. + +@c Emacs 19 feature +If the buffer is read-only, @code{kill-region} modifies the kill ring +just the same, then signals an error without modifying the buffer. This +is convenient because it lets the user use all the kill commands to copy +text into the kill ring from a read-only buffer. +@end deffn + +@deffn Command copy-region-as-kill start end +This command saves the region defined by @var{start} and @var{end} on +the kill ring, but does not delete the text from the buffer. It returns +@code{nil}. It also indicates the extent of the text copied by moving +the cursor momentarily, or by displaying a message in the echo area. + +Don't call @code{copy-region-as-kill} in Lisp programs unless you aim to +support Emacs 18. For Emacs 19, it is better to use @code{kill-new} or +@code{kill-append} instead. @xref{Low Level Kill Ring}. +@end deffn + +@node Yank Commands +@comment node-name, next, previous, up +@subsection Functions for Yanking + + @dfn{Yanking} means reinserting an entry of previously killed text +from the kill ring. + +@deffn Command yank &optional arg +@cindex inserting killed text +This command inserts before point the text in the first entry in the +kill ring. It positions the mark at the beginning of that text, and +point at the end. + +If @var{arg} is a list (which occurs interactively when the user +types @kbd{C-u} with no digits), then @code{yank} inserts the text as +described above, but puts point before the yanked text and puts the mark +after it. + +If @var{arg} is a number, then @code{yank} inserts the @var{arg}th most +recently killed text---the @var{arg}th element of the kill ring list. + +@code{yank} does not alter the contents of the kill ring or rotate it. +It returns @code{nil}. +@end deffn + +@deffn Command yank-pop arg +This command replaces the just-yanked entry from the kill ring with a +different entry from the kill ring. + +This is allowed only immediately after a @code{yank} or another +@code{yank-pop}. At such a time, the region contains text that was just +inserted by yanking. @code{yank-pop} deletes that text and inserts in +its place a different piece of killed text. It does not add the deleted +text to the kill ring, since it is already in the kill ring somewhere. + +If @var{arg} is @code{nil}, then the replacement text is the previous +element of the kill ring. If @var{arg} is numeric, the replacement is +the @var{arg}th previous kill. If @var{arg} is negative, a more recent +kill is the replacement. + +The sequence of kills in the kill ring wraps around, so that after the +oldest one comes the newest one, and before the newest one goes the +oldest. + +The value is always @code{nil}. +@end deffn + +@node Low Level Kill Ring +@subsection Low Level Kill Ring + + These functions and variables provide access to the kill ring at a lower +level, but still convenient for use in Lisp programs. They take care of +interaction with X Window selections. They do not exist in Emacs +version 18. + +@defun current-kill n &optional do-not-move +The function @code{current-kill} rotates the yanking pointer in the +kill ring by @var{n} places, and returns the text at that place in the +ring. + +If the optional second argument @var{do-not-move} is non-@code{nil}, +then @code{current-kill} doesn't alter the yanking pointer; it just +returns the @var{n}th kill forward from the current yanking pointer. + +If @var{n} is zero, indicating a request for the latest kill, +@code{current-kill} calls the value of +@code{interprogram-paste-function} (documented below) before consulting +the kill ring. +@end defun + +@defun kill-new string +This function puts the text @var{string} into the kill ring as a new +entry at the front of the ring. It discards the oldest entry if +appropriate. It also invokes the value of +@code{interprogram-cut-function} (see below). +@end defun + +@defun kill-append string before-p +This function appends the text @var{string} to the first entry in the +kill ring. Normally @var{string} goes at the end of the entry, but if +@var{before-p} is non-@code{nil}, it goes at the beginning. This +function also invokes the value of @code{interprogram-cut-function} (see +below). +@end defun + +@defvar interprogram-paste-function +This variable provides a way of transferring killed text from other +programs, when you are using a window system. Its value should be +@code{nil} or a function of no arguments. + +If the value is a function, @code{current-kill} calls it to get the +``most recent kill''. If the function returns a non-@code{nil} value, +then that value is used as the ``most recent kill''. If it returns +@code{nil}, then the first element of @code{kill-ring} is used. + +The normal use of this hook is to get the X server's primary selection +as the most recent kill, even if the selection belongs to another X +client. @xref{X Selections}. +@end defvar + +@defvar interprogram-cut-function +This variable provides a way of communicating killed text to and from +other programs, when you are using a window system. Its value should be +@code{nil} or a function of one argument. + +If the value is a function, @code{kill-new} and @code{kill-append} call +it with the new first element of the kill ring as an argument. + +The normal use of this hook is to set the X server's primary selection +to the newly killed text. +@end defvar + +@node Internals of Kill Ring +@comment node-name, next, previous, up +@subsection Internals of the Kill Ring + + The variable @code{kill-ring} holds the kill ring contents, in the +form of a list of strings. The most recent kill is always at the front +of the list. + + The @code{kill-ring-yank-pointer} variable points to a link in the +kill ring list, whose @sc{car} is the text to yank next. Moving +@code{kill-ring-yank-pointer} to a different link is called +@dfn{rotating the kill ring}; we say it identifies the ``front'' of the +ring. We call the kill ring a ``ring'' because the functions that move +the yank pointer wrap around from the end of the list to the beginning, +or vice-versa. Rotation of the kill ring is virtual; it does not change +the value of @code{kill-ring}. + + Both @code{kill-ring} and @code{kill-ring-yank-pointer} are Lisp +variables whose values are normally lists. The word ``pointer'' in the +name of the @code{kill-ring-yank-pointer} indicates that the variable's +purpose is to identify one element of the list for use by the next yank +command. + + The value of @code{kill-ring-yank-pointer} is always @code{eq} to one +of the links in the kill ring list. The element it identifies is the +@sc{car} of that link. Kill commands, which change the kill ring, also +set this variable from @code{kill-ring}. The effect is to rotate the +ring so that the newly killed text is at front. + + Here is a diagram that shows the variable @code{kill-ring-yank-pointer} +pointing to the second entry in the kill ring @code{("some text" "a +different piece of text" "yet older text")}. + +@example +@group +kill-ring kill-ring-yank-pointer + | | + | ___ ___ ---> ___ ___ ___ ___ + --> |___|___|------> |___|___|--> |___|___|--> nil + | | | + | | | + | | -->"yet older text" + | | + | --> "a different piece of text" + | + --> "some text" +@end group +@end example + +@noindent +This state of affairs might occur after @kbd{C-y} (@code{yank}) +immediately followed by @kbd{M-y} (@code{yank-pop}). + +@defvar kill-ring +This variable holds list of killed text sequences, most recently killed +first. +@end defvar + +@defvar kill-ring-yank-pointer +This variable's value indicates which element of the kill ring is at the +``front'' of the ring for yanking. More precisely, the value is a tail +of the value of @code{kill-ring}, and its @sc{car} is the kill string +that @kbd{C-y} should yank. +@end defvar + +@defopt kill-ring-max +The value of this variable is the maximum length to which the kill +ring can grow, before elements are thrown away at the end. The default +value for @code{kill-ring-max} is 30. +@end defopt + +@node Undo +@comment node-name, next, previous, up +@section Undo +@cindex redo + + Most buffers have an @dfn{undo list} which records all changes made to +the buffer's text so that they can be undone. (The buffers which don't +have one are usually special-purpose buffers for which Emacs assumes +that undoing is not useful.) All the primitives which modify the text +in the buffer automatically add elements to the front of the undo list, +which is in the variable @code{buffer-undo-list}. + +@defvar buffer-undo-list +This variable's value is the undo list of the current buffer. +A value of @code{t} disables the recording of undo information. +@end defvar + +Here are the kinds of elements an undo list can have: + +@table @code +@item @var{integer} +This kind of element records a previous value of point. Ordinary cursor +motion does not get any sort of undo record, but deletion commands use +these entries to record where point was before the command. + +@item (@var{beg} . @var{end}) +This kind of element indicates how to delete text that was inserted. +Upon insertion, the text occupied the range @var{beg}--@var{end} in the +buffer. + +@item (@var{pos} . @var{deleted}) +This kind of element indicates how to reinsert text that was deleted. +The deleted text itself is the string @var{deleted}. The place to +reinsert it is @var{pos}. + +@item (t @var{high} . @var{low}) +This kind of element indicates that an unmodified buffer became +modified. The elements @var{high} and @var{low} are two integers, each +recording 16 bits of the visited file's modification time as of when it +was previously visited or saved. @code{primitive-undo} uses those +values to determine whether to mark the buffer as unmodified once again; +it does so only if the file's modification time matches those numbers. + +@item (nil @var{property} @var{value} @var{beg} . @var{end}) +This kind of element records a change in a text property. +Here's how you might undo the change: + +@example +(put-text-property @var{beg} @var{end} @var{property} @var{value}) +@end example + +@item nil +This element is a boundary. The elements between two boundaries are +called a @dfn{change group}; normally, each change group corresponds to +one keyboard command, and undo commands normally undo an entire group as +a unit. +@end table + +@defun undo-boundary +This function places a boundary element in the undo list. The undo +command stops at such a boundary, and successive undo commands undo +to earlier and earlier boundaries. This function returns @code{nil}. + +The editor command loop automatically creates an undo boundary between +keystroke commands. Thus, each undo normally undoes the effects of one +command. Calling this function explicitly is useful for splitting the +effects of a command into more than one unit. For example, +@code{query-replace} calls this function after each replacement so that +the user can undo individual replacements one by one. +@end defun + +@defun primitive-undo count list +This is the basic function for undoing elements of an undo list. +It undoes the first @var{count} elements of @var{list}, returning +the rest of @var{list}. You could write this function in Lisp, +but it is convenient to have it in C. + +@code{primitive-undo} adds elements to the buffer's undo list when it +changes the buffer. Undo commands avoid confusion by saving the undo +list value at the beginning of a sequence of undo operations. Then the +undo operations use and update the saved value. The new elements added +by undoing are not part of the saved value, so they don't interfere with +continuing to undo. +@end defun + +@node Maintaining Undo +@section Maintaining Undo Lists + + This section describes how to enable and disable undo information for +a given buffer. It also explains how the undo list is truncated +automatically so it doesn't get too big. + + Recording of undo information in a newly created buffer is normally +enabled to start with; but if the buffer name starts with a space, the +undo recording is initially disabled. You can explicitly enable or +disable undo recording with the following two functions, or by setting +@code{buffer-undo-list} yourself. + +@deffn Command buffer-enable-undo &optional buffer-or-name +This command enables recording undo information for buffer +@var{buffer-or-name}, so that subsequent changes can be undone. If no +argument is supplied, then the current buffer is used. This function +does nothing if undo recording is already enabled in the buffer. It +returns @code{nil}. + +In an interactive call, @var{buffer-or-name} is the current buffer. +You cannot specify any other buffer. +@end deffn + +@defun buffer-disable-undo &optional buffer +@defunx buffer-flush-undo &optional buffer +@cindex disable undo +This function discards the undo list of @var{buffer}, and disables +further recording of undo information. As a result, it is no longer +possible to undo either previous changes or any subsequent changes. If +the undo list of @var{buffer} is already disabled, this function +has no effect. + +This function returns @code{nil}. It cannot be called interactively. + +The name @code{buffer-flush-undo} is not considered obsolete, but the +preferred name @code{buffer-disable-undo} is new as of Emacs versions +19. +@end defun + + As editing continues, undo lists get longer and longer. To prevent +them from using up all available memory space, garbage collection trims +them back to size limits you can set. (For this purpose, the ``size'' +of an undo list measures the cons cells that make up the list, plus the +strings of deleted text.) Two variables control the range of acceptable +sizes: @code{undo-limit} and @code{undo-strong-limit}. + +@defvar undo-limit +This is the soft limit for the acceptable size of an undo list. The +change group at which this size is exceeded is the last one kept. +@end defvar + +@defvar undo-strong-limit +The upper limit for the acceptable size of an undo list. The change +group at which this size is exceeded is discarded itself (along with all +subsequent changes). There is one exception: garbage collection always +keeps the very latest change group no matter how big it is. +@end defvar + +@node Filling +@comment node-name, next, previous, up +@section Filling +@cindex filling, explicit + + @dfn{Filling} means adjusting the lengths of lines (by moving the line +breaks) so that they are nearly (but no greater than) a specified +maximum width. Additionally, lines can be @dfn{justified}, which means +that spaces are inserted between words to make the line exactly the +specified width. The width is controlled by the variable +@code{fill-column}. For ease of reading, lines should be no longer than +70 or so columns. + + You can use Auto Fill mode (@pxref{Auto Filling}) to fill text +automatically as you insert it, but changes to existing text may leave +it improperly filled. Then you must fill the text explicitly. + + Most of the functions in this section return values that are not +meaningful. + +@deffn Command fill-paragraph justify-flag +@cindex filling a paragraph +This command fills the paragraph at or after point. If +@var{justify-flag} is non-@code{nil}, each line is justified as well. +It uses the ordinary paragraph motion commands to find paragraph +boundaries. @xref{Paragraphs,,, emacs, The Emacs Manual}. +@end deffn + +@deffn Command fill-region start end &optional justify-flag +This command fills each of the paragraphs in the region from @var{start} +to @var{end}. It justifies as well if @var{justify-flag} is +non-@code{nil}. + +The variable @code{paragraph-separate} controls how to distinguish +paragraphs. @xref{Standard Regexps}. +@end deffn + +@deffn Command fill-individual-paragraphs start end &optional justify-flag mail-flag +This command fills each paragraph in the region according to its +individual fill prefix. Thus, if the lines of a paragraph were indented +with spaces, the filled paragraph will remain indented in the same +fashion. + +The first two arguments, @var{start} and @var{end}, are the beginning +and end of the region to be filled. The third and fourth arguments, +@var{justify-flag} and @var{mail-flag}, are optional. If +@var{justify-flag} is non-@code{nil}, the paragraphs are justified as +well as filled. If @var{mail-flag} is non-@code{nil}, it means the +function is operating on a mail message and therefore should not fill +the header lines. + +Ordinarily, @code{fill-individual-paragraphs} regards each change in +indentation as starting a new paragraph. If +@code{fill-individual-varying-indent} is non-@code{nil}, then only +separator lines separate paragraphs. That mode can handle paragraphs +with extra indentation on the first line. +@end deffn + +@defopt fill-individual-varying-indent +This variable alters the action of @code{fill-individual-paragraphs} as +described above. +@end defopt + +@deffn Command fill-region-as-paragraph start end &optional justify-flag +This command considers a region of text as a paragraph and fills it. If +the region was made up of many paragraphs, the blank lines between +paragraphs are removed. This function justifies as well as filling when +@var{justify-flag} is non-@code{nil}. In an interactive call, any +prefix argument requests justification. + +In Adaptive Fill mode, which is enabled by default, +@code{fill-region-as-paragraph} on an indented paragraph when there is +no fill prefix uses the indentation of the second line of the paragraph +as the fill prefix. +@end deffn + +@deffn Command justify-current-line +This command inserts spaces between the words of the current line so +that the line ends exactly at @code{fill-column}. It returns +@code{nil}. +@end deffn + +@defopt fill-column +This buffer-local variable specifies the maximum width of filled +lines. Its value should be an integer, which is a number of columns. +All the filling, justification and centering commands are affected by +this variable, including Auto Fill mode (@pxref{Auto Filling}). + +As a practical matter, if you are writing text for other people to +read, you should set @code{fill-column} to no more than 70. Otherwise +the line will be too long for people to read comfortably, and this can +make the text seem clumsy. +@end defopt + +@defvar default-fill-column +The value of this variable is the default value for @code{fill-column} in +buffers that do not override it. This is the same as +@code{(default-value 'fill-column)}. + +The default value for @code{default-fill-column} is 70. +@end defvar + +@node Auto Filling +@comment node-name, next, previous, up +@section Auto Filling +@cindex filling, automatic +@cindex Auto Fill mode + + Auto Fill mode is a minor mode which fills lines automatically as text +as inserted. This section describes the hook and the two variables used +by Auto Fill mode. For a description of functions that you can call +explicitly to fill and justify existing text, see @ref{Filling}. + +@defvar auto-fill-function +The value of this variable should be a function (of no arguments) to +be called after self-inserting a space at a column beyond +@code{fill-column}. It may be @code{nil}, in which case nothing +special is done. + +The value of @code{auto-fill-function} is @code{do-auto-fill} when +Auto-Fill mode is enabled. That is a function whose sole purpose is to +implement the usual strategy for breaking a line. + +@quotation +In older Emacs versions, this variable was named @code{auto-fill-hook}, +but since it is not called with the standard convention for hooks, it +was renamed to @code{auto-fill-function} in version 19. +@end quotation +@end defvar + +@node Sorting +@section Sorting Text +@cindex sorting text + + The sorting functions described in this section all rearrange text in +a buffer. This is in contrast to the function @code{sort}, which +rearranges the order of the elements of a list (@pxref{Rearrangement}). +The values returned by these functions are not meaningful. + +@defun sort-subr reverse nextrecfun endrecfun &optional startkeyfun endkeyfun +This function is the general text sorting routine that divides a buffer +into records and sorts them. Most of the commands in this section use +this function. + +To understand how @code{sort-subr} works, consider the whole accessible +portion of the buffer as being divided into disjoint pieces called +@dfn{sort records}. The records may or may not be contiguous; they may +not overlap. A portion of each sort record (perhaps all of it) is +designated as the sort key. Sorting rearranges the records in order by +their sort keys. + +Usually, the records are rearranged in order of ascending sort key. +If the first argument to the @code{sort-subr} function, @var{reverse}, +is non-@code{nil}, the sort records are rearranged in order of +descending sort key. + +The next four arguments to @code{sort-subr} are functions that are +called to move point across a sort record. They are called many times +from within @code{sort-subr}. + +@enumerate +@item +@var{nextrecfun} is called with point at the end of a record. This +function moves point to the start of the next record. The first record +is assumed to start at the position of point when @code{sort-subr} is +called. Therefore, you should usually move point to the beginning of +the buffer before calling @code{sort-subr}. + +This function can indicate there are no more sort records by leaving +point at the end of the buffer. + +@item +@var{endrecfun} is called with point within a record. It moves point to +the end of the record. + +@item +@var{startkeyfun} is called to move point from the start of a record to +the start of the sort key. This argument is optional; if it is omitted, +the whole record is the sort key. If supplied, the function should +either return a non-@code{nil} value to be used as the sort key, or +return @code{nil} to indicate that the sort key is in the buffer +starting at point. In the latter case, @var{endkeyfun} is called to +find the end of the sort key. + +@item +@var{endkeyfun} is called to move point from the start of the sort key +to the end of the sort key. This argument is optional. If +@var{startkeyfun} returns @code{nil} and this argument is omitted (or +@code{nil}), then the sort key extends to the end of the record. There +is no need for @var{endkeyfun} if @var{startkeyfun} returns a +non-@code{nil} value. +@end enumerate + +As an example of @code{sort-subr}, here is the complete function +definition for @code{sort-lines}: + +@example +@group +;; @r{Note that the first two lines of doc string} +;; @r{are effectively one line when viewed by a user.} +(defun sort-lines (reverse beg end) + "Sort lines in region alphabetically. +Called from a program, there are three arguments: +@end group +@group +REVERSE (non-nil means reverse order), +and BEG and END (the region to sort)." + (interactive "P\nr") + (save-restriction + (narrow-to-region beg end) + (goto-char (point-min)) + (sort-subr reverse + 'forward-line + 'end-of-line))) +@end group +@end example + +Here @code{forward-line} moves point to the start of the next record, +and @code{end-of-line} moves point to the end of record. We do not pass +the arguments @var{startkeyfun} and @var{endkeyfun}, because the entire +record is used as the sort key. + +The @code{sort-paragraphs} function is very much the same, except that +its @code{sort-subr} call looks like this: + +@example +@group +(sort-subr reverse + (function + (lambda () + (skip-chars-forward "\n \t\f"))) + 'forward-paragraph) +@end group +@end example +@end defun + +@deffn Command sort-regexp-fields reverse record-regexp key-regexp start end +This command sorts the region between @var{start} and @var{end} +alphabetically as specified by @var{record-regexp} and @var{key-regexp}. +If @var{reverse} is a negative integer, then sorting is in reverse +order. + +Alphabetical sorting means that two sort keys are compared by +comparing the first characters of each, the second characters of each, +and so on. If a mismatch is found, it means that the sort keys are +unequal; the sort key whose character is less at the point of first +mismatch is the lesser sort key. The individual characters are compared +according to their numerical values. Since Emacs uses the @sc{ASCII} +character set, the ordering in that set determines alphabetical order. +@c version 19 change + +The value of the @var{record-regexp} argument specifies how to divide +the buffer into sort records. At the end of each record, a search is +done for this regular expression, and the text that matches it is the +next record. For example, the regular expression @samp{^.+$}, which +matches lines with at least one character besides a newline, would make +each such line into a sort record. @xref{Regular Expressions}, for a +description of the syntax and meaning of regular expressions. + +The value of the @var{key-regexp} argument specifies what part of each +record is the sort key. The @var{key-regexp} could match the whole +record, or only a part. In the latter case, the rest of the record has +no effect on the sorted order of records, but it is carried along when +the record moves to its new position. + +The @var{key-regexp} argument can refer to the text matched by a +subexpression of @var{record-regexp}, or it can be a regular expression +on its own. + +If @var{key-regexp} is: + +@table @asis +@item @samp{\@var{digit}} +then the text matched by the @var{digit}th @samp{\(...\)} parenthesis +grouping in @var{record-regexp} is the sort key. + +@item @samp{\&} +then the whole record is the sort key. + +@item a regular expression +then @code{sort-regexp-fields} searches for a match for the regular +expression within the record. If such a match is found, it is the sort +key. If there is no match for @var{key-regexp} within a record then +that record is ignored, which means its position in the buffer is not +changed. (The other records may move around it.) +@end table + +For example, if you plan to sort all the lines in the region by the +first word on each line starting with the letter @samp{f}, you should +set @var{record-regexp} to @samp{^.*$} and set @var{key-regexp} to +@samp{\<f\w*\>}. The resulting expression looks like this: + +@example +@group +(sort-regexp-fields nil "^.*$" "\\<f\\w*\\>" + (region-beginning) + (region-end)) +@end group +@end example + +If you call @code{sort-regexp-fields} interactively, it prompts for +@var{record-regexp} and @var{key-regexp} in the minibuffer. +@end deffn + +@deffn Command sort-lines reverse start end +This command alphabetically sorts lines in the region between +@var{start} and @var{end}. If @var{reverse} is non-@code{nil}, the sort +is in reverse order. +@end deffn + +@deffn Command sort-paragraphs reverse start end +This command alphabetically sorts paragraphs in the region between +@var{start} and @var{end}. If @var{reverse} is non-@code{nil}, the sort +is in reverse order. +@end deffn + +@deffn Command sort-pages reverse start end +This command alphabetically sorts pages in the region between +@var{start} and @var{end}. If @var{reverse} is non-@code{nil}, the sort +is in reverse order. +@end deffn + +@deffn Command sort-fields field start end +This command sorts lines in the region between @var{start} and +@var{end}, comparing them alphabetically by the @var{field}th field +of each line. Fields are separated by whitespace and numbered starting +from 1. If @var{field} is negative, sorting is by the +@w{@minus{}@var{field}th} field from the end of the line. This command +is useful for sorting tables. +@end deffn + +@deffn Command sort-numeric-fields field start end +This command sorts lines in the region between @var{start} and +@var{end}, comparing them numerically by the @var{field}th field of each +line. The specified field must contain a number in each line of the +region. Fields are separated by whitespace and numbered starting from +1. If @var{field} is negative, sorting is by the +@w{@minus{}@var{field}th} field from the end of the line. This command +is useful for sorting tables. +@end deffn + +@deffn Command sort-columns reverse &optional beg end +This command sorts the lines in the region between @var{beg} and +@var{end}, comparing them alphabetically by a certain range of columns. +The column positions of @var{beg} and @var{end} bound the range of +columns to sort on. + +If @var{reverse} is non-@code{nil}, the sort is in reverse order. + +One unusual thing about this command is that the entire line +containing position @var{beg}, and the entire line containing position +@var{end}, are included in the region sorted. + +Note that @code{sort-columns} uses the @code{sort} utility program, +and so cannot work properly on text containing tab characters. Use +@kbd{M-x @code{untabify}} to convert tabs to spaces before sorting. + +The @code{sort-columns} function did not work on VMS prior to Emacs 19. +@end deffn + +@node Columns +@comment node-name, next, previous, up +@section Counting Columns +@cindex columns +@cindex counting columns +@cindex horizontal position + + The column functions convert between a character position (counting +characters from the beginning of the buffer) and a column position +(counting screen characters from the beginning of a line). + + A character counts according to the number of columns it occupies on +the screen. This means control characters count as occupying 2 or 4 +columns, depending upon the value of @code{ctl-arrow}, and tabs count as +occupying a number of columns that depends on the value of +@code{tab-width} and on the column where the tab begins. @xref{Usual Display}. + + Column number computations ignore the width of the window and the +amount of horizontal scrolling. Consequently, a column value can be +arbitrarily high. The first (or leftmost) column is numbered 0. + +@defun current-column +This function returns the horizontal position of point, measured in +columns, counting from 0 at the left margin. The column position is the +sum of the widths of all the displayed representations of the characters +between the start of the current line and point. + +For an example of using @code{current-column}, see the description of +@code{count-lines} in @ref{Text Lines}. +@end defun + +@defun move-to-column column &optional force +This function moves point to @var{column} in the current line. The +calculation of @var{column} takes into account the widths of the +displayed representations of the characters between the start of the +line and point. + +If column @var{column} is beyond the end of the line, point moves to the +end of the line. If @var{column} is negative, point moves to the +beginning of the line. + +If it is impossible to move to column @var{column} because that is in +the middle of a multicolumn character such as a tab, point moves to the +end of that character. However, if @var{force} is non-@code{nil}, and +@var{column} is in the middle of a tab, then @code{move-to-column} +converts the tab into spaces so that it can move precisely to column +@var{column}. Other multicolumn characters can cause anomalies despite +@var{force}, since there is no way to split them. + +The argument @var{force} also has an effect if the line isn't long +enough to reach column @var{column}; in that case, it says to indent at +the end of the line to reach that column. + +If @var{column} is not an integer, an error is signaled. + +The return value is the column number actually moved to. +@end defun + +@node Indentation +@section Indentation +@cindex indentation + + The indentation functions are used to examine, move to, and change +whitespace that is at the beginning of a line. Some of the functions +can also change whitespace elsewhere on a line. Columns and indentation +count from zero at the left margin. + +@menu +* Primitive Indent:: Functions used to count and insert indentation. +* Mode-Specific Indent:: Customize indentation for different modes. +* Region Indent:: Indent all the lines in a region. +* Relative Indent:: Indent the current line based on previous lines. +* Indent Tabs:: Adjustable, typewriter-like tab stops. +* Motion by Indent:: Move to first non-blank character. +@end menu + +@node Primitive Indent +@subsection Indentation Primitives + + This section describes the primitive functions used to count and +insert indentation. The functions in the following sections use these +primitives. + +@defun current-indentation +@comment !!Type Primitive Function +@comment !!SourceFile indent.c +This function returns the indentation of the current line, which is +the horizontal position of the first nonblank character. If the +contents are entirely blank, then this is the horizontal position of the +end of the line. +@end defun + +@deffn Command indent-to column &optional minimum +@comment !!Type Primitive Function +@comment !!SourceFile indent.c +This function indents from point with tabs and spaces until +@var{column} is reached. If @var{minimum} is specified and +non-@code{nil}, then at least that many spaces are inserted even if this +requires going beyond @var{column}. The value is the column at which +the inserted indentation ends. +@end deffn + +@defopt indent-tabs-mode +@comment !!SourceFile indent.c +If this variable is non-@code{nil}, indentation functions can insert +tabs as well as spaces. Otherwise, they insert only spaces. Setting +this variable automatically makes it local to the current buffer. +@end defopt + +@node Mode-Specific Indent +@subsection Indentation Controlled by Major Mode + + An important function of each major mode is to customize the @key{TAB} +key to indent properly for the language being edited. This section +describes the mechanism of the @key{TAB} key and how to control it. +The functions in this section return unpredictable values. + +@defvar indent-line-function +This variable's value is the function to be used by @key{TAB} (and +various commands) to indent the current line. The command +@code{indent-according-to-mode} does no more than call this function. + +In Lisp mode, the value is the symbol @code{lisp-indent-line}; in C +mode, @code{c-indent-line}; in Fortran mode, @code{fortran-indent-line}. +In Fundamental mode, Text mode, and many other modes with no standard +for indentation, the value is @code{indent-to-left-margin} (which is the +default value). +@end defvar + +@deffn Command indent-according-to-mode +This command calls the function in @code{indent-line-function} to +indent the current line in a way appropriate for the current major mode. +@end deffn + +@deffn Command indent-for-tab-command +This command calls the function in @code{indent-line-function} to indent +the current line; except that if that function is +@code{indent-to-left-margin}, it calls @code{insert-tab} instead. (That +is a trivial command which inserts a tab character.) +@end deffn + +@defvar left-margin +This variable is the column to which the default +@code{indent-line-function} will indent. (That function is +@code{indent-to-left-margin}.) In Fundamental mode, @key{LFD} indents +to this column. This variable automatically becomes buffer-local when +set in any fashion. +@end defvar + +@defun indent-to-left-margin +This is the default @code{indent-line-function}, used in Fundamental +mode, Text mode, etc. Its effect is to adjust the indentation at the +beginning of the current line to the value specified by the variable +@code{left-margin}. This may involve either inserting or deleting +whitespace. +@end defun + +@deffn Command newline-and-indent +@comment !!SourceFile simple.el +This function inserts a newline, then indents the new line (the one +following the newline just inserted) according to the major mode. + +It does indentation by calling the current @code{indent-line-function}. +In programming language modes, this is the same thing @key{TAB} does, +but in some text modes, where @key{TAB} inserts a tab, +@code{newline-and-indent} indents to the column specified by +@code{left-margin}. +@end deffn + +@deffn Command reindent-then-newline-and-indent +@comment !!SourceFile simple.el +This command reindents the current line, inserts a newline at point, +and then reindents the new line (the one following the newline just +inserted). + +This command does indentation on both lines according to the current +major mode, by calling the current value of @code{indent-line-function}. +In programming language modes, this is the same thing @key{TAB} does, +but in some text modes, where @key{TAB} inserts a tab, +@code{reindent-then-newline-and-indent} indents to the column specified +by @code{left-margin}. +@end deffn + +@node Region Indent +@subsection Indenting an Entire Region + + This section describes commands which indent all the lines in the +region. They return unpredictable values. + +@deffn Command indent-region start end to-column +This command indents each nonblank line starting between @var{start} +(inclusive) and @var{end} (exclusive). If @var{to-column} is +@code{nil}, @code{indent-region} indents each nonblank line by calling +the current mode's indentation function, the value of +@code{indent-line-function}. + +If @var{to-column} is non-@code{nil}, it should be an integer +specifying the number of columns of indentation; then this function +gives each line exactly that much indentation, by either adding or +deleting whitespace. + +If there is a fill prefix, @code{indent-region} indents each line +by making it start with the fill prefix. +@end deffn + +@defvar indent-region-function +The value of this variable is a function that can be used by +@code{indent-region} as a short cut. You should design the function so +that it will produce the same results as indenting the lines of the +region one by one, but presumably faster. + +If the value is @code{nil}, there is no short cut, and +@code{indent-region} actually works line by line. + +A short cut function is useful in modes such as C mode and Lisp mode, +where the @code{indent-line-function} must scan from the beginning of +the function: applying it to each line would be quadratic in time. The +short cut can update the scan information as it moves through the lines +indenting them; this takes linear time. In a mode where indenting a +line individually is fast, there is no need for a short cut. + +@code{indent-region} with a non-@code{nil} argument has a different +meaning and does not use this variable. +@end defvar + +@deffn Command indent-rigidly start end count +@comment !!SourceFile indent.el +This command indents all lines starting between @var{start} +(inclusive) and @var{end} (exclusive) sideways by @var{count} columns. +This ``preserves the shape'' of the affected region, moving it as a +rigid unit. Consequently, this command is useful not only for indenting +regions of unindented text, but also for indenting regions of formatted +code. + +For example, if @var{count} is 3, this command adds 3 columns of +indentation to each of the lines beginning in the region specified. + +In Mail mode, @kbd{C-c C-y} (@code{mail-yank-original}) uses +@code{indent-rigidly} to indent the text copied from the message being +replied to. +@end deffn + +@defun indent-code-rigidly start end columns &optional nochange-regexp +This is like @code{indent-rigidly}, except that it doesn't alter lines +that start within strings or comments. + +In addition, it doesn't alter a line if @var{nochange-regexp} matches at +the beginning of the line (if @var{nochange-regexp} is non-@code{nil}). +@end defun + +@node Relative Indent +@subsection Indentation Relative to Previous Lines + + This section describes two commands which indent the current line +based on the contents of previous lines. + +@deffn Command indent-relative &optional unindented-ok +This command inserts whitespace at point, extending to the same +column as the next @dfn{indent point} of the previous nonblank line. An +indent point is a non-whitespace character following whitespace. The +next indent point is the first one at a column greater than the current +column of point. For example, if point is underneath and to the left of +the first non-blank character of a line of text, it moves to that column +by inserting whitespace. + +If the previous nonblank line has no next indent point (i.e., none at a +great enough column position), @code{indent-relative} either does +nothing (if @var{unindented-ok} is non-@code{nil}) or calls +@code{tab-to-tab-stop}. Thus, if point is underneath and to the right +of the last column of a short line of text, this command ordinarily +moves point to the next tab stop by inserting whitespace. + +The return value of @code{indent-relative} is unpredictable. + +In the following example, point is at the beginning of the second +line: + +@example +@group + This line is indented twelve spaces. +@point{}The quick brown fox jumped. +@end group +@end example + +@noindent +Evaluation of the expression @code{(indent-relative nil)} produces the +following: + +@example +@group + This line is indented twelve spaces. + @point{}The quick brown fox jumped. +@end group +@end example + + In this example, point is between the @samp{m} and @samp{p} of +@samp{jumped}: + +@example +@group + This line is indented twelve spaces. +The quick brown fox jum@point{}ped. +@end group +@end example + +@noindent +Evaluation of the expression @code{(indent-relative nil)} produces the +following: + +@example +@group + This line is indented twelve spaces. +The quick brown fox jum @point{}ped. +@end group +@end example +@end deffn + +@deffn Command indent-relative-maybe +@comment !!SourceFile indent.el +This command indents the current line like the previous nonblank line. +It calls @code{indent-relative} with @code{t} as the @var{unindented-ok} +argument. The return value is unpredictable. + +If the previous nonblank line has no indent points beyond the current +column, this command does nothing. +@end deffn + +@node Indent Tabs +@comment node-name, next, previous, up +@subsection Adjustable ``Tab Stops'' +@cindex tabs stops for indentation + + This section explains the mechanism for user-specified ``tab stops'' +and the mechanisms which use and set them. The name ``tab stops'' is +used because the feature is similar to that of the tab stops on a +typewriter. The feature works by inserting an appropriate number of +spaces and tab characters to reach the next tab stop column; it does not +affect the display of tab characters in the buffer (@pxref{Usual +Display}). Note that the @key{TAB} character as input uses this tab +stop feature only in a few major modes, such as Text mode. + +@deffn Command tab-to-tab-stop +This command inserts spaces or tabs up to the next tab stop column +defined by @code{tab-stop-list}. It searches the list for an element +greater than the current column number, and uses that element as the +column to indent to. It does nothing if no such element is found. +@end deffn + +@defopt tab-stop-list +This variable is the list of tab stop columns used by +@code{tab-to-tab-stops}. The elements should be integers in increasing +order. The tab stop columns need not be evenly spaced. + +Use @kbd{M-x edit-tab-stops} to edit the location of tab stops +interactively. +@end defopt + +@node Motion by Indent +@subsection Indentation-Based Motion Commands + + These commands, primarily for interactive use, act based on the +indentation in the text. + +@deffn Command back-to-indentation +@comment !!SourceFile simple.el +This command moves point to the first non-whitespace character in the +current line (which is the line in which point is located). It returns +@code{nil}. +@end deffn + +@deffn Command backward-to-indentation arg +@comment !!SourceFile simple.el +This command moves point backward @var{arg} lines and then to the +first nonblank character on that line. It returns @code{nil}. +@end deffn + +@deffn Command forward-to-indentation arg +@comment !!SourceFile simple.el +This command moves point forward @var{arg} lines and then to the first +nonblank character on that line. It returns @code{nil}. +@end deffn + +@node Case Changes +@comment node-name, next, previous, up +@section Case Changes +@cindex case changes + + The case change commands described here work on text in the current +buffer. @xref{Character Case}, for case conversion commands that work +on strings and characters. @xref{Case Table}, for how to customize +which characters are upper or lower case and how to convert them. + +@deffn Command capitalize-region start end +This function capitalizes all words in the region defined by +@var{start} and @var{end}. To capitalize means to convert each word's +first character to upper case and convert the rest of each word to lower +case. The function returns @code{nil}. + +If one end of the region is in the middle of a word, the part of the +word within the region is treated as an entire word. + +When @code{capitalize-region} is called interactively, @var{start} and +@var{end} are point and the mark, with the smallest first. + +@example +@group +---------- Buffer: foo ---------- +This is the contents of the 5th foo. +---------- Buffer: foo ---------- +@end group + +@group +(capitalize-region 1 44) +@result{} nil + +---------- Buffer: foo ---------- +This Is The Contents Of The 5th Foo. +---------- Buffer: foo ---------- +@end group +@end example +@end deffn + +@deffn Command downcase-region start end +This function converts all of the letters in the region defined by +@var{start} and @var{end} to lower case. The function returns +@code{nil}. + +When @code{downcase-region} is called interactively, @var{start} and +@var{end} are point and the mark, with the smallest first. +@end deffn + +@deffn Command upcase-region start end +This function converts all of the letters in the region defined by +@var{start} and @var{end} to upper case. The function returns +@code{nil}. + +When @code{upcase-region} is called interactively, @var{start} and +@var{end} are point and the mark, with the smallest first. +@end deffn + +@deffn Command capitalize-word count +This function capitalizes @var{count} words after point, moving point +over as it does. To capitalize means to convert each word's first +character to upper case and convert the rest of each word to lower case. +If @var{count} is negative, the function capitalizes the +@minus{}@var{count} previous words but does not move point. The value +is @code{nil}. + +If point is in the middle of a word, the part of word the before point +(if moving forward) or after point (if operating backward) is ignored. +The rest is treated as an entire word. + +When @code{capitalize-word} is called interactively, @var{count} is +set to the numeric prefix argument. +@end deffn + +@deffn Command downcase-word count +This function converts the @var{count} words after point to all lower +case, moving point over as it does. If @var{count} is negative, it +converts the @minus{}@var{count} previous words but does not move point. +The value is @code{nil}. + +When @code{downcase-word} is called interactively, @var{count} is set +to the numeric prefix argument. +@end deffn + +@deffn Command upcase-word count +This function converts the @var{count} words after point to all upper +case, moving point over as it does. If @var{count} is negative, it +converts the @minus{}@var{count} previous words but does not move point. +The value is @code{nil}. + +When @code{upcase-word} is called interactively, @var{count} is set to +the numeric prefix argument. +@end deffn + +@node Text Properties +@section Text Properties +@cindex text properties +@cindex attributes of text +@cindex properties of text + + Each character position in a buffer or a string can have a @dfn{text +property list}, much like the property list of a symbol (@pxref{Property +Lists}). The properties belong to a particular character at a +particular place, such as, the letter @samp{T} at the beginning of this +sentence or the first @samp{o} in @samp{foo}---if the same character +occurs in two different places, the two occurrences generally have +different properties. + + Each property has a name and a value. Both of these can be any Lisp +object, but the name is normally a symbol. The usual way to access the +property list is to specify a name and ask what value corresponds to it. + + If a character has a @code{category} property, we call it the +@dfn{category} of the character. It should be a symbol. The properties +of the symbol serve as defaults for the properties of the character. + + Copying text between strings and buffers preserves the properties +along with the characters; this includes such diverse functions as +@code{substring}, @code{insert}, and @code{buffer-substring}. + +@menu +* Examining Properties:: Looking at the properties of one character. +* Changing Properties:: Setting the properties of a range of text. +* Property Search:: Searching for where a property changes value. +* Special Properties:: Particular properties with special meanings. +* Sticky Properties:: How inserted text gets properties from + neighboring text. +* Saving Properties:: Saving text properties in files, and reading + them back. +* Not Intervals:: Why text properties do not use + Lisp-visible text intervals. +@end menu + +@node Examining Properties +@subsection Examining Text Properties + + The simplest way to examine text properties is to ask for the value of +a particular property of a particular character. For that, use +@code{get-text-property}. Use @code{text-properties-at} to get the +entire property list of a character. @xref{Property Search}, for +functions to examine the properties of a number of characters at once. + + These functions handle both strings and buffers. Keep in mind that +positions in a string start from 0, whereas positions in a buffer start +from 1. + +@defun get-text-property pos prop &optional object +This function returns the value of the @var{prop} property of the +character after position @var{pos} in @var{object} (a buffer or +string). The argument @var{object} is optional and defaults to the +current buffer. + +If there is no @var{prop} property strictly speaking, but the character +has a category which is a symbol, then @code{get-text-property} returns +the @var{prop} property of that symbol. +@end defun + +@defun get-char-property pos prop &optional object +This function is like @code{get-text-property}, except that it checks +overlays first and then text properties. @xref{Overlays}. + +The argument @var{object} may be a string, a buffer, or a window. If it +is a window, then the buffer displayed in that window is used for text +properties and overlays, but only the overlays active for that window +are considered. If @var{object} is a buffer, then all overlays in that +buffer are considered, as well as text properties. If @var{object} is a +string, only text properties are considered, since strings never have +overlays. +@end defun + +@defun text-properties-at position &optional object +This function returns the entire property list of the character at +@var{position} in the string or buffer @var{object}. If @var{object} is +@code{nil}, it defaults to the current buffer. +@end defun + +@node Changing Properties +@subsection Changing Text Properties + + The primitives for changing properties apply to a specified range of +text. The function @code{set-text-properties} (see end of section) sets +the entire property list of the text in that range; more often, it is +useful to add, change, or delete just certain properties specified by +name. + + Since text properties are considered part of the buffer's contents, and +can affect how the buffer looks on the screen, any change in the text +properties is considered a buffer modification. Buffer text property +changes are undoable (@pxref{Undo}). + +@defun add-text-properties start end props &optional object +This function modifies the text properties for the text between +@var{start} and @var{end} in the string or buffer @var{object}. If +@var{object} is @code{nil}, it defaults to the current buffer. + +The argument @var{props} specifies which properties to change. It +should have the form of a property list (@pxref{Property Lists}): a list +whose elements include the property names followed alternately by the +corresponding values. + +The return value is @code{t} if the function actually changed some +property's value; @code{nil} otherwise (if @var{props} is @code{nil} or +its values agree with those in the text). + +For example, here is how to set the @code{comment} and @code{face} +properties of a range of text: + +@example +(add-text-properties @var{start} @var{end} + '(comment t face highlight)) +@end example +@end defun + +@defun put-text-property start end prop value &optional object +This function sets the @var{prop} property to @var{value} for the text +between @var{start} and @var{end} in the string or buffer @var{object}. +If @var{object} is @code{nil}, it defaults to the current buffer. +@end defun + +@defun remove-text-properties start end props &optional object +This function deletes specified text properties from the text between +@var{start} and @var{end} in the string or buffer @var{object}. If +@var{object} is @code{nil}, it defaults to the current buffer. + +The argument @var{props} specifies which properties to delete. It +should have the form of a property list (@pxref{Property Lists}): a list +whose elements are property names alternating with corresponding values. +But only the names matter---the values that accompany them are ignored. +For example, here's how to remove the @code{face} property. + +@example +(remove-text-properties @var{start} @var{end} '(face nil)) +@end example + +The return value is @code{t} if the function actually changed some +property's value; @code{nil} otherwise (if @var{props} is @code{nil} or +if no character in the specified text had any of those properties). +@end defun + +@defun set-text-properties start end props &optional object +This function completely replaces the text property list for the text +between @var{start} and @var{end} in the string or buffer @var{object}. +If @var{object} is @code{nil}, it defaults to the current buffer. + +The argument @var{props} is the new property list. It should be a list +whose elements are property names alternating with corresponding values. + +After @code{set-text-properties} returns, all the characters in the +specified range have identical properties. + +If @var{props} is @code{nil}, the effect is to get rid of all properties +from the specified range of text. Here's an example: + +@example +(set-text-properties @var{start} @var{end} nil) +@end example +@end defun + +@node Property Search +@subsection Property Search Functions + +In typical use of text properties, most of the time several or many +consecutive characters have the same value for a property. Rather than +writing your programs to examine characters one by one, it is much +faster to process chunks of text that have the same property value. + +Here are functions you can use to do this. In all cases, @var{object} +defaults to the current buffer. + +For high performance, it's very important to use the @var{limit} +argument to these functions, especially the ones that search for a +single property---otherwise, they may spend a long time considering +changes in other properties while scanning to the end of the buffer. + +@defun next-property-change pos &optional object limit +The function scans the text forward from position @var{pos} in the +string or buffer @var{object} till it finds a change in some text +property, then returns the position of the change. In other words, it +returns the position of the first character beyond @var{pos} whose +properties are not identical to those of the character just after +@var{pos}. + +If @var{limit} is non-@code{nil}, then the scan ends at position +@var{limit}. If there is no property change before that point, +@code{next-property-change} returns @var{limit}. + +The value is @code{nil} if the properties remain unchanged all the way +to the end of @var{object} and @var{limit} is @code{nil}. + +If the value is non-@code{nil}, it is a position greater than or equal +to @var{pos}. The value equals @var{pos} only when @var{limit} equals +@var{pos}. + +Here is an example of how to scan the buffer by chunks of text within +which all properties are constant: + +@smallexample +(while (not (eobp)) + (let ((plist (text-properties-at (point))) + (next-change + (or (next-property-change (point) (current-buffer)) + (point-max)))) + @r{Process text from point to @var{next-change}@dots{}} + (goto-char next-change))) +@end smallexample +@end defun + +@defun next-single-property-change pos prop &optional object limit +The function scans the text forward from position @var{pos} in the +string or buffer @var{object} till it finds a change in the @var{prop} +property, then returns the position of the change. In other words, it +returns the position of the first character beyond @var{pos} whose +@var{prop} property differs from that of the character just after +@var{pos}. + +If @var{limit} is non-@code{nil}, then the scan ends at position +@var{limit}. If there is no property change before that point, +@code{next-single-property-change} returns @var{limit}. + +The value is @code{nil} if the property remains unchanged all the way to +the end of @var{object} and @var{limit} is @code{nil}. If the value is +non-@code{nil}, it is a position greater than or equal to @var{pos}; it +equals @var{pos} only if @var{limit} equals @var{pos}. +@end defun + +@defun previous-property-change pos &optional object limit +This is like @code{next-property-change}, but scans back from @var{pos} +instead of forward. If the value is non-@code{nil}, it is a position +less than or equal to @var{pos}; it equals @var{pos} only if @var{limit} +equals @var{pos}. + +Remember that a position is always between two characters; the position +returned by this function is between two characters with different +properties. +@end defun + +@defun previous-single-property-change pos prop &optional object limit +This is like @code{next-property-change}, but scans back from @var{pos} +instead of forward. If the value is non-@code{nil}, it is a position +less than or equal to @var{pos}; it equals @var{pos} only if @var{limit} +equals @var{pos}. +@end defun + +@defun text-property-any start end prop value &optional object +This function returns non-@code{nil} if at least one character between +@var{start} and @var{end} has a property @var{prop} whose value is +@var{value}. More precisely, it returns the position of the first such +character. Otherwise, it returns @code{nil}. + +The optional fifth argument, @var{object}, specifies the string or +buffer to scan. Positions are relative to @var{object}. The default +for @var{object} is the current buffer. +@end defun + +@defun text-property-not-all start end prop value &optional object +This function returns non-@code{nil} if at least one character between +@var{start} and @var{end} has a property @var{prop} whose value differs +from @var{value}. More precisely, it returns the position of the +first such character. Otherwise, it returns @code{nil}. + +The optional fifth argument, @var{object}, specifies the string or +buffer to scan. Positions are relative to @var{object}. The default +for @var{object} is the current buffer. +@end defun + +@node Special Properties +@subsection Properties with Special Meanings + +@table @code +@cindex category of text character +@kindex category @r{(text property)} +@item category +If a character has a @code{category} property, we call it the +@dfn{category} of the character. It should be a symbol. The properties +of the symbol serve as defaults for the properties of the character. + +@item face +@cindex face codes of text +@kindex face @r{(text property)} +You can use the property @code{face} to control the font and color of +text. @xref{Faces}, for more information. This feature is temporary; +in the future, we may replace it with other ways of specifying how to +display text. + +@item mouse-face +@kindex mouse-face @r{(text property)} +The property @code{mouse-face} is used instead of @code{face} when the +mouse is on or near the character. For this purpose, ``near'' means +that all text between the character and where the mouse is have the same +@code{mouse-face} property value. + +@item local-map +@cindex keymap of character +@kindex local-map @r{(text property)} +You can specify a different keymap for a portion of the text by means +of a @code{local-map} property. The property's value, for the character +after point, replaces the buffer's local map. @xref{Active Keymaps}. + +@item read-only +@cindex read-only character +@kindex read-only @r{(text property)} +If a character has the property @code{read-only}, then modifying that +character is not allowed. Any command that would do so gets an error. + +Insertion next to a read-only character is an error if inserting +ordinary text there would inherit the @code{read-only} property due to +stickiness. Thus, you can control permission to insert next to +read-only text by controlling the stickiness. @xref{Sticky Properties}. + +Since changing properties counts as modifying the buffer, it is not +possible to remove a @code{read-only} property unless you know the +special trick: bind @code{inhibit-read-only} to a non-@code{nil} value +and then remove the property. @xref{Read Only Buffers}. + +@item invisible +@kindex invisible @r{(text property)} +A non-@code{nil} @code{invisible} property means a character does not +appear on the screen. This works much like selective display. Details +of this feature are likely to change in future versions, so check the +@file{etc/NEWS} file in the version you are using. + +@item modification-hooks +@cindex change hooks for a character +@cindex hooks for changing a character +@kindex modification-hooks @r{(text property)} +If a character has the property @code{modification-hooks}, then its +value should be a list of functions; modifying that character calls all +of those functions. Each function receives two arguments: the beginning +and end of the part of the buffer being modified. Note that if a +particular modification hook function appears on several characters +being modified by a single primitive, you can't predict how many times +the function will be called. + +@item insert-in-front-hooks +@itemx insert-behind-hooks +@kindex insert-in-front-hooks @r{(text property)} +@kindex insert-behind-hooks @r{(text property)} +Assuming insertion is allowed, it then calls the functions +listed in the @code{insert-in-front-hooks} property of the following +character and in the @code{insert-behind-hooks} property of the +preceding character. These functions receive two arguments, the +beginning and end of the inserted text. + +See also @ref{Change Hooks}, for other hooks that are called +when you change text in a buffer. + +@item point-entered +@itemx point-left +@cindex hooks for motion of point +@kindex point-entered @r{(text property)} +@kindex point-left @r{(text property)} +The special properties @code{point-entered} and @code{point-left} +record hook functions that report motion of point. Each time point +moves, Emacs compares these two property values: + +@itemize @bullet +@item +the @code{point-left} property of the character after the old location, +and +@item +the @code{point-entered} property of the character after the new +location. +@end itemize + +@noindent +If these two values differ, each of them is called (if not @code{nil}) +with two arguments: the old value of point, and the new one. + +The same comparison is made for the characters before the old and new +locations. The result may be to execute two @code{point-left} functions +(which may be the same function) and/or two @code{point-entered} +functions (which may be the same function). The @code{point-left} +functions are always called before the @code{point-entered} functions. + +A primitive function may examine characters at various positions +without moving point to those positions. Only an actual change in the +value of point runs these hook functions. +@end table + +@defvar inhibit-point-motion-hooks +When this variable is non-@code{nil}, @code{point-left} and +@code{point-entered} hooks are not run. +@end defvar + +@node Sticky Properties +@subsection Stickiness of Text Properties +@cindex sticky text properties +@cindex inheritance of text properties + + Self-inserting characters normally take on the same properties as the +preceding character. This is called @dfn{inheritance} of properties. + + In a Lisp program, you can do insertion with inheritance or without, +depending on your choice of insertion primitive. The ordinary text +insertion functions such as @code{insert} do not inherit any properties. +They insert text with precisely the properties of the string being +inserted, and no others. This is correct for programs that copy text +from one context to another---for example, into or out of the kill +ring. To insert with inheritance, use the special primatives described +in this section. + + When you do insertion with inheritance, @emph{which} properties are +inherited depends on two specific properties: @code{front-sticky} and +@code{rear-nonsticky}. + + Insertion after a character inherits those of its properties that are +@dfn{rear-sticky}. Insertion before a character inherits those of its +properties that are @dfn{front-sticky}. By default, a text property is +rear-sticky but not front-sticky. Thus, the default is to inherit all +the properties of the preceding character, and nothing from the +following character. You can request different behavior by specifying +the stickiness of certain properties. + + If a character's @code{front-sticky} property is @code{t}, then all +its properties are front-sticky. If the @code{front-sticky} property is +a list, then the sticky properties of the character are those whose +names are in the list. For example, if a character has a +@code{front-sticky} property whose value is @code{(face read-only)}, +then insertion before the character can inherit its @code{face} property +and its @code{read-only} property, but no others. + + The @code{rear-nonsticky} works the opposite way. Every property is +rear-sticky by default, so the @code{rear-nonsticky} property says which +properties are @emph{not} rear-sticky. If a character's +@code{rear-nonsticky} property is @code{t}, then none of its properties +are rear-sticky. If the @code{rear-nonsticky} property is a list, +properties are rear-sticky @emph{unless} their names are in the list. + + When you insert text with inheritance, it inherits all the rear-sticky +properties of the preceding character, and all the front-sticky +properties of the following character. The previous character's +properties take precedence when both sides offer different sticky values +for the same property. + + Here are the functions that insert text with inheritance of properties: + +@defun insert-and-inherit &rest strings +Insert the strings @var{strings}, just like the function @code{insert}, +but inherit any sticky properties from the adjoining text. +@end defun + +@defun insert-before-markers-and-inherit &rest strings +Insert the strings @var{strings}, just like the function +@code{insert-before-markers}, but inherit any sticky properties from the +adjoining text. +@end defun + +@node Saving Properties +@subsection Saving Text Properites in Files +@cindex text properties in files +@cindex saving text properties + + You can save text properties in files, and restore text properties +when inserting the files, using these two hooks: + +@defvar write-region-annotation-functions +This variable's value is a list of functions for @code{write-region} to +run to encode text properties in some fashion as annotations to the text +being written in the file. @xref{Writing to Files}. + +Each function in the list is called with two arguments: the start and +end of the region to be written. These functions should not alter the +contents of the buffer. Instead, they should return lists indicating +annotations to write in the file in addition to the text in the +buffer. + +Each function should return a list of elements of the form +@code{(@var{position} . @var{string})}, where @var{position} is an +integer specifying the relative position in the text to be written, and +@var{string} is the annotation to add there. + +Each list returned by one of these functions must be already sorted in +increasing order by @var{position}. If there is more than one function, +@code{write-region} merges the lists destructively into one sorted list. + +When @code{write-region} actually writes the text from the buffer to the +file, it intermixes the specified annotations at the corresponding +positions. All this takes place without modifying the buffer. +@end defvar + +@defvar after-insert-file-functions +This variable holds a list of functions for @code{insert-file-contents} +to call after inserting a file's contents. These functions should scan +the inserted text for annotations, and convert them to the text +properties they stand for. + +Each function receives one argument, the length of the inserted text; +point indicates the start of that text. The function should scan that +text for annotations, delete them, and create the text properties that +the annotations specify. The function should return the updated length +of the inserted text, as it stands after those changes. The value +returned by one function becomes the argument to the next function. + +These functions should always return with point at the beginning of +the inserted text. + +The intended use of @code{after-insert-file-functions} is for converting +some sort of textual annotations into actual text properties. But other +uses may be possible. +@end defvar + +We invite users to write Lisp programs to store and retrieve text +properties in files, using these hooks, and thus to experiment with +various data formats and find good ones. Eventually we hope users +will produce good, general extensions we can install in Emacs. + +We suggest not trying to handle arbitrary Lisp objects as property +names or property values---because a program that general is probably +difficult to write, and slow. Instead, choose a set of possible data +types that are reasonably flexible, and not too hard to encode. + +@node Not Intervals +@subsection Why Text Properties are not Intervals +@cindex intervals + + Some editors that support adding attributes to text in the buffer do +so by letting the user specify ``intervals'' within the text, and adding +the properties to the intervals. Those editors permit the user or the +programmer to determine where individual intervals start and end. We +deliberately provided a different sort of interface in Emacs Lisp to +avoid certain paradoxical behavior associated with text modification. + + If the actual subdivision into intervals is meaningful, that means you +can distinguish between a buffer that is just one interval with a +certain property, and a buffer containing the same text subdivided into +two intervals, both of which have that property. + + Suppose you take the buffer with just one interval and kill part of +the text. The text remaining in the buffer is one interval, and the +copy in the kill ring (and the undo list) becomes a separate interval. +Then if you yank back the killed text, you get two intervals with the +same properties. Thus, editing does not preserve the distinction +between one interval and two. + + Suppose we ``fix'' this problem by coalescing the two intervals when +the text is inserted. That works fine if the buffer originally was a +single interval. But suppose instead that we have two adjacent +intervals with the same properties, and we kill the text of one interval +and yank it back. The same interval-coalescence feature that rescues +the other case causes trouble in this one: after yanking, we have just +one interval. One again, editing does not preserve the distinction +between one interval and two. + + Insertion of text at the border between intervals also raises +questions that have no satisfactory answer. + + However, it is easy to arrange for editing to behave consistently for +questions of the form, ``What are the properties of this character?'' +So we have decided these are the only questions that make sense; we have +not implemented asking questions about where intervals start or end. + + In practice, you can usually use the property search functions in +place of explicit interval boundaries. You can think of them as finding +the boundaries of intervals, assuming that intervals are always +coalesced whenever possible. @xref{Property Search}. + + Emacs also provides explicit intervals as a presentation feature; see +@ref{Overlays}. + +@node Substitution +@section Substituting for a Character Code + + The following functions replace characters within a specified region +based on their character codes. + +@defun subst-char-in-region start end old-char new-char &optional noundo +@cindex replace characters +This function replaces all occurrences of the character @var{old-char} +with the character @var{new-char} in the region of the current buffer +defined by @var{start} and @var{end}. + +@cindex Outline mode +@cindex undo avoidance +If @var{noundo} is non-@code{nil}, then @code{subst-char-in-region} +does not record the change for undo and does not mark the buffer as +modified. This feature is useful for changes which are not considered +significant, such as when Outline mode changes visible lines to +invisible lines and vice versa. + +@code{subst-char-in-region} does not move point and returns +@code{nil}. + +@example +@group +---------- Buffer: foo ---------- +This is the contents of the buffer before. +---------- Buffer: foo ---------- +@end group + +@group +(subst-char-in-region 1 20 ?i ?X) + @result{} nil + +---------- Buffer: foo ---------- +ThXs Xs the contents of the buffer before. +---------- Buffer: foo ---------- +@end group +@end example +@end defun + +@defun translate-region start end table +This function applies a translation table to the characters in the +buffer between positions @var{start} and @var{end}. + +The translation table @var{table} is a string; @code{(aref @var{table} +@var{ochar})} gives the translated character corresponding to +@var{ochar}. If the length of @var{table} is less than 256, any +characters with codes larger than the length of @var{table} are not +altered by the translation. + +The return value of @code{translate-region} is the number of +characters which were actually changed by the translation. This does +not count characters which were mapped into themselves in the +translation table. + +This function is available in Emacs versions 19 and later. +@end defun + +@node Registers +@section Registers +@cindex registers + + A register is a sort of variable used in Emacs editing that can hold a +marker, a string, a rectangle, a window configuration (of one frame), or +a frame configuration (of all frames). Each register is named by a +single character. All characters, including control and meta characters +(but with the exception of @kbd{C-g}), can be used to name registers. +Thus, there are 255 possible registers. A register is designated in +Emacs Lisp by a character which is its name. + + The functions in this section return unpredictable values unless +otherwise stated. +@c Will change in version 19 + +@defvar register-alist +This variable is an alist of elements of the form @code{(@var{name} . +@var{contents})}. Normally, there is one element for each Emacs +register that has been used. + +The object @var{name} is a character (an integer) identifying the +register. The object @var{contents} is a string, marker, or list +representing the register contents. A string represents text stored in +the register. A marker represents a position. A list represents a +rectangle; its elements are strings, one per line of the rectangle. +@end defvar + +@defun get-register reg +This function returns the contents of the register +@var{reg}, or @code{nil} if it has no contents. +@end defun + +@defun set-register reg value +This function sets the contents of register @var{reg} to @var{value}. +A register can be set to any value, but the other register functions +expect only certain data types. The return value is @var{value}. +@end defun + +@deffn Command view-register reg +This command displays what is contained in register @var{reg}. +@end deffn + +@ignore +@deffn Command point-to-register reg +This command stores both the current location of point and the current +buffer in register @var{reg} as a marker. +@end deffn + +@deffn Command jump-to-register reg +@deffnx Command register-to-point reg +@comment !!SourceFile register.el +This command restores the status recorded in register @var{reg}. + +If @var{reg} contains a marker, it moves point to the position stored in +the marker. Since both the buffer and the location within the buffer +are stored by the @code{point-to-register} function, this command can +switch you to another buffer. + +If @var{reg} contains a window configuration or a frame configuration. +@code{jump-to-register} restores that configuration. +@end deffn +@end ignore + +@deffn Command insert-register reg &optional beforep +This command inserts contents of register @var{reg} into the current +buffer. + +Normally, this command puts point before the inserted text, and the +mark after it. However, if the optional second argument @var{beforep} +is non-@code{nil}, it puts the mark before and point after. +You can pass a non-@code{nil} second argument @var{beforep} to this +function interactively by supplying any prefix argument. + +If the register contains a rectangle, then the rectangle is inserted +with its upper left corner at point. This means that text is inserted +in the current line and underneath it on successive lines. + +If the register contains something other than saved text (a string) or +a rectangle (a list), currently useless things happen. This may be +changed in the future. +@end deffn + +@ignore +@deffn Command copy-to-register reg start end &optional delete-flag +This command copies the region from @var{start} to @var{end} into +register @var{reg}. If @var{delete-flag} is non-@code{nil}, it deletes +the region from the buffer after copying it into the register. +@end deffn + +@deffn Command prepend-to-register reg start end &optional delete-flag +This command prepends the region from @var{start} to @var{end} into +register @var{reg}. If @var{delete-flag} is non-@code{nil}, it deletes +the region from the buffer after copying it to the register. +@end deffn + +@deffn Command append-to-register reg start end &optional delete-flag +This command appends the region from @var{start} to @var{end} to the +text already in register @var{reg}. If @var{delete-flag} is +non-@code{nil}, it deletes the region from the buffer after copying it +to the register. +@end deffn + +@deffn Command copy-rectangle-to-register reg start end &optional delete-flag +This command copies a rectangular region from @var{start} to @var{end} +into register @var{reg}. If @var{delete-flag} is non-@code{nil}, it +deletes the region from the buffer after copying it to the register. +@end deffn + +@deffn Command window-configuration-to-register reg +This function stores the window configuration of the selected frame in +register @var{reg}. +@end deffn + +@deffn Command frame-configuration-to-register reg +This function stores the current frame configuration in register +@var{reg}. +@end deffn +@end ignore + +@node Change Hooks +@section Change Hooks +@cindex change hooks +@cindex hooks for text changes + + These hook variables let you arrange to take notice of all changes in +all buffers (or in a particular buffer, if you make them buffer-local). +See also @ref{Special Properties}, for how to detect changes to specific +parts of the text. + + The functions you use in these hooks should save and restore the match +data if they do anything that uses regular expressions; otherwise, they +will interfere in bizarre ways with the editing operations that call +them. + +@defvar before-change-function +If this variable is non-@code{nil}, then it should be a function; the +function is called before any buffer modification. Its arguments are +the beginning and end of the region that is about to change, +represented as integers. The buffer that is about to change is always +the current buffer. +@end defvar + +@defvar after-change-function +If this variable is non-@code{nil}, then it should be a function; the +function is called after any buffer modification. It receives three +arguments: the beginning and end of the region just changed, and the +length of the text that existed before the change. (To get the +current length, subtract the region beginning from the region end.) +All three arguments are integers. The buffer that's about to change +is always the current buffer. +@end defvar + +Both of these variables are temporarily bound to @code{nil} during the +time that either of these hooks is running. This means that if one of +these functions changes the buffer, that change won't run these +functions. If you do want the hook function to run recursively, +design your hook functions to bind these variables back to their usual +values. + +@defvar first-change-hook +This variable is a normal hook that is run whenever a buffer is changed +that was previously in the unmodified state. +@end defvar + + The variables described in this section are meaningful only starting +with Emacs version 19. |