|
DataMuseum.dkPresents historical artifacts from the history of: DKUUG/EUUG Conference tapes |
This is an automatic "excavation" of a thematic subset of
See our Wiki for more about DKUUG/EUUG Conference tapes Excavated with: AutoArchaeologist - Free & Open Source Software. |
top - metrics - downloadIndex: T l
Length: 52165 (0xcbc5) Types: TextFile Names: »lispref-6«
└─⟦a05ed705a⟧ Bits:30007078 DKUUG GNU 2/12/89 └─⟦c06c473ab⟧ »./UNRELEASED/lispref.tar.Z« └─⟦1b57a2ffe⟧ └─⟦this⟧ »lispref-6«
Info file: lispref, -*-Text-*- produced by texinfo-format-buffer from file: lispref.texinfo This file documents GNU Emacs Lisp. This is Edition 0.1 Beta of the GNU Emacs Lisp Reference Manual, for Emacs Version 18, with some references to Emacs Version 19. Please read this document for review purposes. Published by the Free Software Foundation, 675 Massachusetts Avenue, Cambridge, MA 02139 USA Copyright (C) 1989 Free Software Foundation, Inc. Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies. Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one. Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions, except that this permission notice may be stated in a translation approved by the Foundation. ▶1f◀ File: lispref Node: Control Structures, Prev: Macros, Up: Top, Next: Evaluation Control Structures ****************** A Lisp program consists of expressions or "forms" (*Note Forms::). We control the order of execution of the forms by enclosing them in "control structures". Control structures are special forms which control when, whether, or how many times to execute the forms they contain. The simplest control structure is sequential execution: first form A, then form B, and so on. This is what happens when you write several forms in succession in the body of a function, or at top level in a file of Lisp code. The forms are executed in the order they are written. We call this "textual order". For example, if a function body consists of two forms A and B, evaluation of the function causes A to be evaluated before B, and the result is the value of B. Naturally, Emacs Lisp has other kinds of control structures, including other varieties of sequencing, function calls, conditionals, iteration, and (controlled) jumps. These control structures are special forms since their subforms are not necessarily evaluated. You can use macros to define your own control structure constructs (*Note Macros::). * Menu: * Sequencing:: Evaluation in textual order. * Conditionals:: if, cond. * Combining Conditions:: and, or, not. * Iteration:: while. * Nonlocal Exits:: Jumping out of a sequence. * Beeping:: Audible signal to user ▶1f◀ File: lispref Node: Sequencing, Prev: Control Structures, Up: Control Structures, Next: Conditionals Sequencing ========== Evaluating forms in the order they are written is the most common control structure. Sometimes this happens automatically, such as in a function body. Elsewhere you must use a control structure construct to do this: `progn', the simplest control construct of Lisp. A `progn' special form looks like this: (progn A B C ...) and it says to execute the forms A, B, C and so on, in that order. These forms are called the body of the `progn' form. The result of the last form in the body becomes the result of the entire `progn'. When Lisp was young, `progn' was the only way to execute two or more forms in succession and use the value of the last of them. But programmers found they often needed to use a `progn' in the body of a function, where (at that time) only one form was allowed. So the body of a function was made into an ``implicit `progn''': several forms are allowed just as in the body of an actual `progn'. Many other control structures likewise contain an implicit `progn'. As a result, `progn' is not used as often as it used to be. It is needed now most often inside of an `unwind-protect', `and' or `or'. * Special form: progn FORMS... This special form evaluates all of the FORMS, in textual order, returning the result of the final form. (progn (print "The first form") (print "The second form") (print "The third form")) -| "The first form" -| "The second form" -| "The third form" => "The third form" Two other control constructs likewise evaluate a series of forms but return a different value: * Special form: prog1 FORM1 FORMS... This special form evaluates FORM1 and all of the FORMS, in textual order, returning the result of the first form. (prog1 (print "The first form") (print "The second form") (print "The third form")) -| "The first form" -| "The second form" -| "The third form" => "The first form" Here is a way to remove the first element from a list in the variable `x', then go ahead and use that element: (foo (prog1 (car x) (setq x (cdr x)))) * Special form: prog2 FORM1 FORM2 FORMS... This special form evaluates FORM1, FORM2, and all of the following FORMS, in textual order, returning the result of the second form. (prog2 (print "The first form") (print "The second form") (print "The third form")) -| "The first form" -| "The second form" -| "The third form" => "The second form" ▶1f◀ File: lispref Node: Conditionals, Prev: Sequencing, Up: Control Structures, Next: Combining Conditions Conditionals ============ Conditional control structures choose among alternatives. Emacs Lisp has two conditional forms: `if', which is much the same as in other languages, and `cond', which is a generalized case statement. * Special form: if CONDITION THEN-FORM ELSE-FORMS... `if' chooses between the THEN-FORM and the ELSE-FORMS based on the value of CONDITION. If the evaluated CONDITION is non-`nil', THEN-FORM is evaluated and the result returned. Otherwise, the ELSE-FORMS are evaluated in textual order, and the value of the last one is returned. (The ELSE part of `if' is an example of an implicit `progn'. *Note Sequencing::.) If CONDITION has the value `nil', and no ELSE-FORMS are given, `if' returns `nil'. `if' is a special form because the branch which is not selected is not evaluated at all. It is completely ignored. Thus, in the example below, `true' is not printed because `print' is never called. (if nil (print 'true) 'very-false) => very-false * Special form: cond CLAUSE... `cond' chooses among an arbitrary number of alternatives. Each CLAUSE in the `cond' must be a list. The CAR of this list is the CONDITION; the remaining elements, if any, the BODY-FORMS. Thus, a clause looks like this: (CONDITION BODY-FORM...) `cond' tries the clauses in textual order, by evaluating the CONDITION of each clause. If the value of CONDITION is non-`nil', the BODY-FORMS are evaluated, and the value of the last BODY-FORM becomes the value of the `cond'. The remaining clauses are ignored. If the value of CONDITION is `nil', the clause ``fails'', so the following clause is tried. If no CONDITION evaluates to non-`nil', so that every clause fails, `cond' returns `nil'. In the following example, if the value of `x' is a number, then it is returned, but if `x' is not a number, then Emacs tests whether it is a string; and if is not a string, Emacs tests whether it is a symbol. (cond ((numberp x) x) ((stringp x) x) ((symbolp x) (symbol-value x))) A clause may also look like this: (CONDITION) Then, if CONDITION is non-`nil' when tested, the value of CONDITION becomes the value of the `cond' form. Often we want the last clause to be executed whenever none of the previous clauses was successful. To do this, we use `t' as the CONDITION of the clause, like this: `(t BODY-FORMS)'. The form `t' evaluates to `t', and that is never `nil', so this clause never fails, provided the `cond' gets to it at all. For example, (cond ((eq a 1) 'foo) (t "default")) => "default" This expression is a `cond' which returns `foo' if the value of `a' is 1, and returns the string `"default"' otherwise. Both `cond' and `if' can be written in terms of the other. Therefore, the choice between them is a matter taste and style. For example: (if A B C) == (cond ((A B) (t C)) ▶1f◀ File: lispref Node: Combining Conditions, Prev: Conditionals, Up: Control Structures, Next: Iteration Constructs for Combining Conditions =================================== This section describes three constructs that are often used in combination with `if' and `cond' to combine conditional expressions. In themselves, `and' and `or' are a kind of multiple conditional construct. * Function: not CONDITION This function tests for the falsehood of CONDITION. It returns `t' if CONDITION is `nil', and `nil' otherwise. The function `not' is identical to `null', but we recommend using `null' if you are testing for an empty list. * Special form: and CONDITIONS... The `and' special form tests whether all the CONDITIONS are true. It works by evaluating the CONDITIONS one by one. If any of the CONDITIONS evaluates to `nil', then the result of the `and' is already determined to be `nil'; so the remaining CONDIDTIONS are ignored and the `and' returns right away. If all the CONDITIONS turn out non-`nil', then the value of the last of them becomes the value of the `and'. Here is an example. The first condition returns the integer 1, which is not `nil'; similarly, the second condition returns the integer 2, which is not `nil'. The third condition is `nil', so the remaining condition is never evaluated. (and (print 1) (print 2) nil (print 3)) -| 1 -| 2 => nil Here is a more realistic example of using `and': (if (and (consp foo) (eq (car foo) 'x)) (message "foo is a list starting with x")) Note that `(car foo)' is not executed if `(consp foo)' returns `nil', thus avoiding an error. `and' can be expressed in terms of either `if' or `cond'. For example: (and ARG1 ARG2 ARG3) == (if ARG1 (if ARG2 ARG3)) == (cond (ARG1 (cond (ARG2 ARG3)))) * Special form: or CONDITION... The `or' special form tests whether at least one CONDITION is true. It works by evaluating each CONDITION one by one. If any CONDITION evaluates to a non-`nil' value; then the result of the `or' is already determined to be non-`nil'; so every remaining CONDITION is ignored and the `or' returns right away. The value it returns is the value of the CONDITION just evaluated. If every CONDITION turns out `nil', then the `or' expression returns `nil'. For example, this expression tests whether `x' is either 0 or `nil'. (or (eq x nil) (= x 0)) Like the `and' function, `or' can be written in terms of `cond'. For example: (or ARG1 ARG2 ARG3) == (cond (ARG1) (ARG2) (ARG3)) You could almost write `or' in terms of `if', but not quite: (if ARG1 ARG1 (if ARG2 ARG2 ARG3)) This is not correct because Emacs can evaluate ARG1 or ARG2 twice, and `(or ARG1' ARG2 ARG3) never does so more than once. ▶1f◀ File: lispref Node: Iteration, Prev: Combining Conditions, Up: Control Structures, Next: Nonlocal Exits Iteration ========= Iteration means executing part of a program repetitively. For example, you might want to repeat some expressions once for each element of a list, or once for each integer from 0 to N. You can do this in Emacs Lisp with the special form `while': * Special form: while CONDITION FORMS... `while' first evaluates CONDITION. If the result is non-`nil', it evaluates FORMS in textual order. Then it re-evaluates CONDITION, repeating this process until CONDITION evaluates to `nil'. There is no limit on the number of iterations that may occur. The loop will continue until either CONDITION evaluates to `nil' or until an error or `throw' jumps out of it (*Note Nonlocal Exits::). The value of a `while' form is always `nil'. (setq num 0) => 0 (while (< num 4) (princ (format "Iteration %d." num)) (setq num (1+ num))) -| Iteration 0. -| Iteration 1. -| Iteration 2. -| Iteration 3. => nil ▶1f◀ File: lispref Node: Nonlocal Exits, Prev: Iteration, Up: Control Structures, Next: Beeping Nonlocal Exits ============== A nonlocal exit is a transfer of control from one point in a program to another remote point. Nonlocal exits can occur in Emacs Lisp as a result of errors; you can also use them under explicit control. * Menu: * Catch and Throw:: * Examples of Catch:: * Errors:: * Cleanups:: ▶1f◀ File: lispref Node: Catch and Throw, Prev: Nonlocal Exits, Up: Nonlocal Exits, Next: Examples of Catch Explicit Nonlocal Exits: `catch' and `throw' -------------------------------------------- Most control constructs affect only the flow of control within the construct itself. The function `throw' is the sole exception: it performs a nonlocal exit on command. `throw' is used inside a `catch', and jumps back to that `catch'. For example: (catch 'foo (progn ... (throw 'foo t) ...)) The `throw' transfers control straight back to the corresponding `catch', which returns immediately. The code following the `throw' is not executed. The second argument of `throw' is used as the return value of the `catch'. The `throw' and the `catch' are matched through the first argument: `throw' searches for a `catch' whose first argument is `eq' to the one specified. Thus, in the above example, the `throw' specifies `foo', and the `catch' specifies the same symbol, so that `catch' does apply. If there is more than one `catch' that matches, the innermost one wins. All Lisp constructs between the `catch' and the `throw', including function calls, are exited automatically along with the `catch'. When binding constructs such as `let' or function calls are exited in this way, the bindings are unbound, just as they are when the binding construct is exited normally (*Note Local Variables::). Likewise, the buffer and position saved by `save-excursion' are restored, and so are the buffer restrictions saved by `save-restriction' and the window selection saved by `save-window-excursion'. Any cleanups established with the `unwind-protect' special form are executed if the `unwind-protect' is exited with a `throw'. The `throw' need not appear lexically within the `catch' that it jumps to. It can equally well be called from another function called within the `catch'. As long as the `throw' takes place chronologically after entry to the `catch', and chronologically before exit from it, it has access to that `catch'. This is why `throw' can be used in commands such as `exit-recursive-edit' which throw back to the Emacs command loop (*Note Recursive Editing::). Common Lisp Note: Most other versions of Lisp, including Common Lisp, have several ways of transferring control nonsequentially: `return', `return-from', and `go', for example. Emacs Lisp has only `throw'. * Special form: catch TAG BODY... `catch' establishes a return point for the `throw' function. The return point is distinguished from other such return points by TAG, which may be any Lisp object. The argument TAG is evaluated normally before the return point is established. With the return point in effect, the forms of the BODY are evaluated in textual order. If the forms execute normally, without error or nonlocal exit, the value of the last body form is returned from the `catch'. If, instead, a `throw' is done specifying the same value TAG, the `catch' exits immediately; the value it returns is whatever was specified as the second argument of `throw'. * Function: throw TAG VALUE The purpose of `throw' is to return from a return point previously established with `catch'. The argument TAG is used to choose among the various existing return points; it must be `eq' to the value specified in the `catch'. If multiple return points match TAG, the innermost one is used. The argument VALUE is used as the value to return from that `catch'. If no return point is in effect with tag TAG, then a `no-catch' error is signaled with data `(TAG VALUE)'. ▶1f◀ File: lispref Node: Examples of Catch, Prev: Catch and Throw, Up: Nonlocal Exits, Next: Errors Examples of `catch' and `throw' ------------------------------- One way to use `catch' and `throw' is to exit from a doubly nested loop. (In most languages, this would be done with a ``go to''.) Here we compute `(foo I J)' for I and J varying from 0 to 9: (defun search-foo () (catch 'loop (let ((i 0)) (while (< i 10) (let ((j 0)) (while (< j 10) (if (foo i j) (throw 'loop (list i j))) (setq j (1+ j)))) (setq i (1+ i)))))) If `foo' ever returns non-`nil', we stop immediately and return a list of I and J. If `foo' always returns `nil', the `catch' returns normally, and the value is `nil', since that is the result of the `while'. Here are two tricky examples, slighly different, showing two return points at once. First, two return points with the same tag, `hack': (defun catch2 (tag) (catch tag (throw 'hack 'yes))) => catch2 (catch 'hack (print (catch2 'hack)) 'no) -| yes => no Since both return points have tags that match the `throw', it goes to the inner one, the one established in `catch2'. Therefore, `catch2' returns normally with value `yes', and this value is printed. Finally the second body form in the outer `catch', which is `'no', is evaluated and returned from the outer `catch'. Now let's change the argument given to `catch2': (defun catch2 (tag) (catch tag (throw 'hack 'yes))) => catch2 (catch 'hack (print (catch2 'quux)) 'no) => yes We still have two return points, but this time only the outer one has the tag `hack'; the inner one has the tag `quux' instead. Therefore, the `throw' returns the value `yes' from the outer return point. The function `print' is never called, and the body-form `'no' is never evaluated. ▶1f◀ File: lispref Node: Errors, Prev: Examples of Catch, Up: Nonlocal Exits, Next: Cleanups Errors ------ When Emacs Lisp attempts to evaluate a form that, for some reason, cannot be evaluated, it "signals" an "error". When an error occurs, Emacs's default reaction is to print an error message and terminate execution of the current command. This is the right thing in most cases, such as if you type `C-f' at the end of the buffer. In complicated programs, simple termination may not be what you want. For example, the program may have made temporary changes in data structures, or created temporary buffers which must, at all costs, be deleted before the program is finished. In such cases, you would use `unwind-protect' to establish "cleanup expressions" to be evaluated in case of error. Occasionally, you may wish the program to continue execution despite an error in a subroutine. In these cases, you would use `condition-case' to establish "error handlers" to recover control in case of error. Each error has an associated "error symbol" or "error name" which identifies the event that caused the problem. The error symbol is useful for programs that handle some kinds of error, but not all. * Menu: * Signalling Errors:: * Processing of Errors:: * Handling Errors:: * Error Names:: ▶1f◀ File: lispref Node: Signalling Errors, Prev: Errors, Up: Errors, Next: Processing of Errors How to Signal an Error ...................... Most errors are signaled ``automatically'' within Lisp primitives which you call for other purposes, such as if you try to take the CAR of an integer or move forward a character at the end of the buffer; but you can signal them explicitly with the functions `error' and `signal'. * Function: error FORMAT-STRING &rest ARGS This function signals an error with an error message constructed by applying `format' (*Note Conversion of Characters and Strings::) to FORMAT-STRING and ARGS. Typical uses of `error' is shown in the following examples: (error "You have committed an error. Try doing something different.") error--> You have committed an error. Try doing something different. (error "You have committed %d errors. You don't learn fast." 10) error--> You have committed 10 errors. You don't learn fast. `error' works by calling `signal' with the error symbol `error' and the string returned by `format' as the only arguments. * Function: signal ERROR-SYMBOL DATA This function signals an error named by ERROR-SYMBOL. The argument DATA is a list of additional Lisp objects relevant to the circumstances of the error. ERROR-SYMBOL must have an `error-conditions' property whose value is a list of condition names. *Note Error Names::, for a description of how to set up your own error conditions. The number and significance of the objects in DATA depends on ERROR-SYMBOL. For example, in an `wrong-type-arg' error, there are two objects in the list: a predicate which describes the type that was expected, and the object which failed to fit that type. Both ERROR-SYMBOL and DATA are available to any error handlers which handle the error: a list `(ERROR-SYMBOL . DATA)' is constructed to become the value of the local variable bound in the `condition-case' form. If the error is not handled, both of them are used in printing the error message. (signal 'wrong-number-of-arguments '(x y)) error--> Wrong number of arguments: x, y (signal 'no-such-error '("My unknown error condition.")) error--> peculiar error: "My unknown error condition." Common Lisp Note: The function `signal' is the sole function that can signal an error (the `error' function calls it). This implies that Emacs Lisp has nothing like the Common Lisp concept of continuable errors. ▶1f◀ File: lispref Node: Processing of Errors, Prev: Signalling Errors, Up: Errors, Next: Handling Errors How Emacs Processes Errors .......................... When an error is signaled, Emacs searches for an active "handler" for the error. A handler is a specially marked place in the Lisp code of the current function or any of the functions by which it was called. If an applicable handler exists, its code is executed, and control resumes following the handler. The handler executes in the environment of the `condition-case' which established it; all functions called within that `condition-case' have already been exited, and the handler cannot return to them. If no applicable handler is in effect in your program, the current command is terminated and control returns to the editing command loop, because the command loop has its own handler for all kinds of errors. The command loop's handler uses the error symbol and associated data to print an error message. If no handler applies, the Lisp debugger may be called. The debugger is enabled if the variable `debug-on-error' (*Note Debug Functions::) is non-`nil'. Unlike error handlers, the debugger runs in the environment of the error, so that you can examine values of variables precisely as they were at the time of the error. *Note Debugging::, for the details. ▶1f◀ File: lispref Node: Handling Errors, Prev: Processing of Errors, Up: Errors, Next: Error Names Handling Errors ............... The usual effect of signaling an error is to terminate the command that is running and return immediately to the Emacs editing command loop. You can arrange to trap errors occuring in a part of your program by establishing an "error handler" with the special form `condition-case'. A simple example looks like this: (condition-case nil (delete-file filename) (error nil)) This deletes the file, catching any error that occurs and returning `nil'. The second argument of `condition-case' is called the "protected form". (In the example above, that is a call to `delete-file'.) The error handlers go into effect when this form begins execution and are deactivated when this form returns. They remain in effect for all the intervening time. In particular, they are in effect during the execution of subroutines called by this form, and their subroutines, and so on. This is a good thing, since, strictly speaking, errors can be signaled only by Lisp primitives, not by the protected form itself. The arguments after the second one are handlers. Each handler lists one or more "condition names" (which are symbols) to specify which errors it will handle. The error symbol specified when an error is signaled also defines a list of condition names. A handler applies to an error if they have any condition names in common. In the example above, there is one handler, and it specifies one condition name, `error'. That condition includes all errors. The search for an applicable handler checks all the established handlers starting with the most recently established one. Thus, if two nested `condition-case' forms try to handle the same error, the inner of the two will actually handle it. When an error is handled, control returns to the handler, executing the cleanups of all `unwind-protect' forms that are exited by doing so. Then, the body of the handler is executed. After this, execution continues by returning from the `condition-case' form. Because the protected form is exited completely before execution of the handler, the handler cannot resume execution at the point of the error, nor can it examine variable bindings that were made within the protected form. All it can do is clean up and proceed. Error signaling and handling have some resemblance to `throw' and `catch', but they are entirely separate facilities. An error cannot be caught by a `catch', and a `throw' cannot be handled by an error handler (though if there is no `catch', `throw' will signal an error which can be handled). * Special form: condition-case VAR PROTECTED-FORM HANDLERS... This special form establishes the error handlers HANDLERS around the execution of PROTECTED-FORM. If PROTECTED-FORM executes without error, the value it returns becomes the value of the `condition-case' form; in this case, the `condition-case' has no effect. The `condition-case' form makes a difference when an error occurs during PROTECTED-FORM. Each of the HANDLERS is a list of the form `(CONDITIONS BODY...)'. CONDITIONS is a condition name to be handled, or a list of condition names; BODY is one or more Lisp expressions to be executed when this handler handles an error. Each error that occurs has an "error symbol" which describes what kind of error it is. The `error-conditions' property of this symbol is a list of condition names (*Note Error Names::). Emacs searches all the active `condition-case' forms for a handler which specifies one or more of these names; the innermost matching `condition-case' handles the error. The handlers in this `condition-case' are tested in the order in which they appear. The body of the handler is then executed, and the `condition-case' returns normally, using the value of the last form in the body as the overall value. The argument VAR is a variable. `condition-case' does not bind this variable when executing the PROTECTED-FORM, only when it handles an error. At that time, VAR is bound locally to a list of the form `(ERROR-SYMBOL . DATA)', giving the particulars of the error. The handler can refer to this list to decide what to do. For example, if the error is for failure opening a file, the file name is the second element of DATA---the third element of VAR. Here is an example of using `condition-case' to handle the error that results from dividing by zero. The handler prints out a warning message and returns a very large number. (defun safe-divide (dividend divisor) (condition-case err ;; Protected form. (/ dividend divisor) ;; The handler. (arith-error ; Condition. (princ (format "Arithmetic error: %s" err)) 1000000))) => safe-divide (safe-divide 5 0) -| Arithmetic error: (arith-error) => 1000000 The handler specifies condition name `arith-error' so that it will handle only division-by-zero errors. Other kinds of errors will not be handled, at least not by this `condition-case'. Thus, (safe-divide nil 3) error--> Wrong type argument: 0, nil Here is a `condition-case' that catches all kinds of errors, including those signaled with `error': (setq baz 34) => 34 (condition-case err (if (eq baz 35) t ;; This is a call to the function `error'. (error "Rats! The variable %s was %s, not 35." 'baz baz)) ;; This is the handler; it is not a form. (error (princ (format "The error was: %s" err)) 2)) -| The error was: (error "Rats! The variable baz was 34, not 35.") => 2 `condition-case' may be used to trap errors that are unexpected, such as in a function that executes an expression read from the user. It may also be used to trap errors that are expected, such as failure to open a file when you call `insert-file-contents'. ▶1f◀ File: lispref Node: Error Names, Prev: Handling Errors, Up: Errors Error Symbols and Condition Names ................................. When you signal an error, you specify an "error symbol" to specify the kind of error you have in mind. Each error has one and only one error symbol to categorize it. This is the finest classification of errors defined by the Lisp language. These narrow classifications are grouped into a hierarchy of wider classes called "error conditions", identified by "condition names". The narrowest such classes belong to the error symbols themselves: each error symbol is also a condition name. There are also condition names for more extensive classes, up to the condition name `error' which takes in all kinds of errors. Thus, each error has one or more condition names: `error', the error symbol if that is distinct from `error', and perhaps some intermediate classifications. In order for a symbol to be usable as an error symbol, it must have an `error-conditions' property which gives a list of condition names. This list defines the conditions which this kind of error belongs to. (The error symbol itself, and the symbol `error', should always be members of this list.) Thus, the hierarchy of condition names is defined by the `error-conditions' properties of the error symbols. In addition to the `error-conditions' list, the error symbol should have an `error-message' property whose value is a string to be printed when that error is signaled but not handled. If the `error-message' property exists, but is not a string, the untrappable `peculiar error' will be signaled. Here is how we define a new error symbol, `new-error', and how we would then signal it: (put 'new-error 'error-conditions '(error my-own-errors new-error)) => (error my-own-errors new-error) (put 'new-error 'error-message "A new error") => "A new error" This error has three condition names: `new-error', the narrowest classification; `my-own-errors', which we imagine is a wider classification; and `error', which is the widest of all. Naturally, Emacs will never signal a `new-error' on its own; only an explicit call to `signal' (*Note Errors::) in your code can do this: (signal 'new-error '(x y)) error--> A new error: x, y This error can be handled through any of the three condition names. This example handles `new-error' and any other errors in the class `my-own-errors': (condition-case foo (bar nil t) (my-own-errors nil)) The significant way that errors are classified is by their condition names. They are the names used to match errors with handlers. An error symbol serves only as a convenient way to specify the intended error message and list of condition names. Lisp could have been designed differently, so that `signal' would need a list of condition names rather than one error symbol, but that would have made it more cumbersome. By contrast, using only error symbols without condition names would seriously decrease the power of `condition-case'. Condition names make it possible to categorize errors at various levels of generality when you write an error handler. Using error symbols alone would eliminate all but the narrowest level of classification. In the appendix (*Note Standard Errors::) is a list of all the standard error symbols and their conditions. ▶1f◀ File: lispref Node: Cleanups, Prev: Errors, Up: Nonlocal Exits Cleaning up from Nonlocal Exits ------------------------------- The `unwind-protect' construct is essential whenever you temporarily put a data structure in an inconsistent state; it permits you to make sure to make the data consistent in the event of an error. * Special form: unwind-protect BODY CLEANUP-FORMS... `unwind-protect' executes the BODY with a guarantee that the CLEANUP-FORMS will be evaluated if control leaves BODY, no matter how that happens. The BODY may complete normally, or execute a `throw' over the `unwind-protect', or cause an error; in all cases, the CLEANUP-FORMS will be evaluated. Only the BODY is actually protected by the `unwind-protect'. If any of the CLEANUP-FORMS themselves exit (e.g., via a `throw' or an error), it is *not* guaranteed that the rest of them will be executed. If the failure of one of the CLEANUP-FORMS has the potential to cause trouble, then it should be protected by another `unwind-protect' around that form. The number of currently active `unwind-protect' forms counts, together with the number of local variable bindings, against the limit `max-specpdl-size' (*Note Local Variables::). For example, you might make an invisible buffer for temporary use, which you wish to be sure to kill before the next command: (save-excursion (let ((buffer (get-buffer-create " *temp*"))) (set-buffer buffer) (unwind-protect BODY (kill-buffer buffer)))) You might think that we could just as well write `(kill-buffer (current-buffer))' and dispense with the variable `buffer'. However, the way shown above safer, if BODY happens to get an error after switching to a different buffer! (Alternatively, you could write another `save-excursion' around the body, to ensure that the temporary buffer becomes current in time to kill it.) Here is an actual example taken from the file `ftp.el'. It creates a process (*Note Processes::) to try to establish a connection to a remote machine. As the function `ftp-login' is highly susceptible to numerous problems which the writer of the function cannot anticipate, it is protected with a form that guarantees deletion of the process in the event of failure. Otherwise, Emacs might fill up with useless subprocesses. (let ((win nil)) (unwind-protect (progn (setq process (ftp-setup-buffer host file)) (if (setq win (ftp-login process host user password)) (message "Logged in") (error "Ftp login failed"))) (or win (and process (delete-process process))))) This example actually has a small bug: if the user types `C-g' to quit, and the quit happens immediately after the function `ftp-setup-buffer' returns but before the variable `process' is set, the process will not be killed. There is no easy way to fix this bug, but at least it is very unlikely. ▶1f◀ File: lispref Node: Beeping, Prev: Nonlocal Exits, Up: Control Structures Beeping ======= You can make Emacs ring a bell, beep, or perhaps, blink the screen. This attracts attention. If too frequent, the action is irritating. Be careful not to use beeping when an error message is appropriate. (*Note Errors::.) * Function: ding &optional DONT-TERMINATE This function beeps, or flashes the screen (see `visible-bell' below). It also terminates any keyboard macro currently executing unless DONT-TERMINATE is non-`nil'. * Function: beep &optional DONT-TERMINATE This is a synonym for `ding'. * Variable: visible-bell This global variable determines whether Emacs will try to flash the screen to represent a bell. `t' means do, `nil' means don't. This is only effective if the termcap entry for the terminal in use has the visible bell flag (vb) set. ▶1f◀ File: lispref Node: Evaluation, Prev: Control Structures, Up: Top, Next: Loading Evaluation ********** The "evaluation" of objects in Emacs Lisp invokes the "Lisp interpreter". The Lisp interpreter, which is actually the `eval' function described below, looks at the object it is given, and computes its "value as an expression" in a fashion depending on the object's type. * Menu: * Intro Eval:: Evaluation in the scheme of things. * Eval:: The Lisp interpreter. * Forms:: The objects to be evaluated. * Quoting:: Avoiding evaluation. ▶1f◀ File: lispref Node: Intro Eval, Prev: Evaluation, Up: Evaluation, Next: Eval Introduction to Evaluation ========================== The "evaluation" of objects in Emacs Lisp invokes the "Lisp interpreter". The Lisp interpreter, which is actually the `eval' function described below, looks at the object it is given, and returns its "value as an expression" in a fashion depending on the object's type. Any object can be evaluated, but in practice only numbers, symbols, lists and strings are evaluated very often. A Lisp object which is intended for evaluation is called an "expression" or a "form". The fact that expressions are data objects, not merely text, is one of the fundamental differences between Lisp-like languages and typical programming languages. First, evaluation is not command key interpretation. The editing command loop interprets keyboard input using the current keymaps, and then uses `call-interactively' to invoke the command. The execution of the command itself usually involves evaluation, but that is another matter. (*Note Command Loop::.) Second, evaluation does not result from simply reading a form. Reading produces the form itself, not the value of the form. It converts the printed representation of the form to a Lisp object, which *is* the form in the strict sense. Evaluation is a recursive process. That is, evaluation of a form may cause `eval' to be called again to evaluate parts of the form. For example, evaluation of a function call first causes evaluation of each argument of the function call, and then evaluation of each form in the function. Consider the form `(car x)': the subform `x' is first evaluated recursively, so that its value can be passed as an argument to the function `car'. The evaluation of forms takes place in a context called the "environment". This consists of the ambient, inherited values and bindings of all Lisp variables. Whenever the form refers to a variable without creating a new binding for it, the value of the ambient binding is used. (*Note Variables::.) Evaluation of a form may create new environments for nested, recursive evaluation by binding variables (*Note Local Variables::). These environments are temporary and will be gone by the time evaluation of the form is complete. The form may also make changes that persist; these changes are called "side-effects". An example of a form that produces side-effects is `(setq foo 1)'. Finally, evaluation of one particular function call, `byte-code', invokes the "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 it may invoke the Lisp interpreter. (*Note Byte Compilation::.) The details of what evaluation means for each kind of form are described later (*Note Forms::). ▶1f◀ File: lispref Node: Eval, Prev: Intro Eval, Up: Evaluation, Next: Forms Eval ==== Most forms, most of the time, are evaluated automatically, by virtue of their occurence in a program. But on rare occasions, you may need to write code that evaluates a form; for example, if the form is found in a file being edited. On these occasions, use the `eval' function. The functions and variables described in this section evaluate forms, specify limits to the evaluation process, or record recently returned values. Evaluation is also performed by calling `apply' and `funcall' (*Note Calling Functions::) and `load' (*Note Loading::). The details of what evaluation means for each kind of form are described in another section; *Note Forms::. * Function: eval FORM This is the basic function that performs evaluation. It evaluates FORM in the current environment, and returns the result. How the evaluation proceeds depends on the type of the object (*Note Forms::). Since `eval' is a function, the argument expression you write for it is evaluated twice: once as preparation before `eval' is called, and again by the `eval' function itself. Here is an example: (setq foo 'bar) => bar (setq bar 'baz) => baz ;; `eval' is called on the form `bar', which is the value of `foo' (eval foo) => baz The number of currently active calls to `eval' is limited to `max-lisp-eval-depth'. * Command: eval-current-buffer &optional STREAM This function evaluates the forms in the current buffer. It reads forms from the buffer and calls `eval' on them until the end of the buffer is reached, or an error is signaled and not handled. If STREAM is supplied, the variable `standard-output' is bound to STREAM during the evaluation (*Note Output Functions::). `eval-current-buffer' always returns `nil'. * Command: eval-region START END &optional STREAM This function evaluates forms in the current buffer in the region defined by the positions START and END. It reads forms from the region and calls `eval' on them until the end of the region is reached, or an error is signaled and not handled. If STREAM is supplied, `standard-output' is bound to it for the duration of the evaluation. `eval-region' always returns `nil'. * Variable: max-specpdl-size This variable defines the limit on the number of local variable bindings and `unwind-protect' cleanups (*Note Nonlocal Exits::) that are allowed before the error `error' is signaled (with data `"Variable binding depth exceeds max-specpdl-size"'). This limit and the associated error when it is exceeded is one way that Lisp avoids infinite recursion on an ill-defined function. The default value is 600. * Variable: max-lisp-eval-depth This variable defines the maximum depth allowed in calls to `eval', `apply', and `funcall' before the error `error' is signaled (with data `"Lisp nesting exceeds max-lisp-eval-depth"'). `eval' is called recursively to evaluate the arguments of Lisp function calls and to evaluate bodies of functions. This limit and the associated error when it is exceeded is one way that Lisp avoids infinite recursion on an ill-defined function. The default value is 200. If you set it to a value less than 100, Lisp will reset it to 100. * Variable: values The value of this variable is a list of values returned by all expressions which were read from buffers (including the minibuffer), evaluated, and printed. The elements are in order, most recent first. (setq x 1) => 1 (list 'A (1+ 2) auto-save-default) => (A 3 t) values => ((A 3 t) 1 ...) This variable is useful for referring back to values of forms you have evaluated. It is generally a bad idea to examine the value of `values' directly, since it may be very long. Instead, examine particular elements, like this: ;; Refer to the most recent evaluation result. (nth 0 values) => (A 3 t) ;; That put a new element on, so all elements move back one. (nth 1 values) => (A 3 t) (nth 3 values) => 1 ▶1f◀ File: lispref Node: Forms, Prev: Eval, Up: Evaluation, Next: Quoting Kinds of Forms ============== Any Lisp object that we intend to evaluate is a "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'. All three kinds are described in this section, 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 * Nonempty List Forms:: Function and macro calls, and special forms ▶1f◀ File: lispref Node: Self-Evaluating Forms, Prev: Forms, Up: Forms, Next: Symbol Forms Self-Evaluating Forms --------------------- A "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 `"foo"' evaluates to the string `"foo"'. Likewise, evaluation of a vector does not cause evaluation of the elements of the vector---it returns that very vector. '123 ; An object, shown without evaluation. => 123 123 ; Evaluated as usual---result is the same. => 123 (eval '123) ; Evaluated ``by hand''---result is the same. => 123 (eval (eval '123)) ; Evaluating twice changes nothing. => 123 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 it is inconvenient and not useful; but it is possible to put them inside Lisp programs when they are constructed *as Lisp objects*. Here is an example: ;; Build such an expression. (setq buffer (list 'print (current-buffer))) => (print #<buffer evaluation.texinfo>) ;; Evaluate it. (eval buffer) -| #<buffer evaluation.texinfo>) => #<buffer evaluation.texinfo>) ▶1f◀ File: lispref Node: Symbol Forms, Prev: Self-Evaluating Forms, Up: Forms, Next: Nonempty List Forms Symbol Forms ------------ 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), you get an error. For more information on the binding of variables, *Note Variables::. In the following example, the value cell of a symbol is set to a value (with `setq'). When the symbol is then evaluated, that value is returned. (setq a 123) => 123 (eval 'a) => 123 a => 123 Two symbols, `nil' and `t', are special, because the value of `nil' is always `nil' and the value of `t' is always `t'. Thus, these two symbols act like self-evaluating forms, even though `eval' treats them like any other symbol. ▶1f◀ File: lispref Node: Nonempty List Forms, Prev: Symbol Forms, Up: Forms Nonempty List Forms ------------------- A form which 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 rest of the list consists of "arguments" for the function, macro or special form. * Menu: * Classifying Lists:: * Function Forms:: * Macro Forms:: * Special Forms:: * Autoloading:: ▶1f◀ File: lispref Node: Classifying Lists, Prev: Nonempty List Forms, Up: Nonempty List Forms, Next: Function Forms Classification of List Forms ---------------------------- 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 *not* evaluated, as it would be in some dialects of Lisp languages, such as Scheme. If the first element of the list is a symbol, as it most commonly is, then the symbol's function cell is examined. If the object referenced by the function cell is another symbol, the function cell of that symbol is examined, and used exactly as if it had been the original symbol. If that is another symbol, this process, called "symbol function indirection", is repeated until a non-symbol is obtained. One possible consequence of this process is an infinite loop, if a symbol's function cell refers to the same symbol. Or a symbol may have a void function cell, causing a `void-function' error. But if neither of these things happens, we eventually obtain a non-symbol, which ought to a function or a related object. More precisely, we should now have a Lisp function (a lambda expression), 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 `invalid-function' is signaled. The following example illustrates the symbol indirection process. We use `fset' to set the function cell of a symbol and `symbol-function' to get the function cell contents (*Note Function Cells::). In this way we store the symbol `car' into the function cell of `first', and the symbol `first' into the function cell of `erste'. ;; Build this function cell linkage: ;; ------------- ----- ------- ------- ;; | #<subr car> | <-- | car | <-- | first | <-- | erste | ;; ------------- ----- ------- ------- (symbol-function 'car) => #<subr car> (fset 'first 'car) => car (fset 'erste 'first) => first (erste '(1 2 3)) ; Call the function referenced by `erste'. => 1 By contrast, the following example calls a function without any symbol function indirection, because the first element is not a symbol, but rather an anonymous Lisp function. ((lambda (arg) (erste arg)) '(1 2 3)) => 1 However, after that function is called, its body is evaluated; this does involve symbol function indirection when calling `erste'. ▶1f◀