17.1 debug

Suppose you have written a function definition that is intended to return the sum of the numbers 1 through a given number. (This is the triangle function discussed earlier. See Example with Decrementing Counter, for a discussion.)

However, your function definition has a bug. You have mistyped ‘1=’ for ‘1-’. Here is the broken definition:

(defun triangle-bugged (number)
  "Return sum of numbers 1 through NUMBER inclusive."
  (let ((total 0))
    (while (> number 0)
      (setq total (+ total number))
      (setq number (1= number)))      ; Error here.
    total))

If you are reading this in Info, you can evaluate this definition in the normal fashion. You will see triangle-bugged appear in the echo area.

Now evaluate the triangle-bugged function with an argument of 4:

(triangle-bugged 4)

This will create and enter a *Backtrace* buffer that says:

---------- Buffer: *Backtrace* ----------
Debugger entered--Lisp error: (void-function 1=)
  (1= number)
  (setq number (1= number))
  (while (> number 0) (setq total (+ total number))
        (setq number (1= number)))
  (let ((total 0)) (while (> number 0) (setq total ...)
    (setq number ...)) total)
  triangle-bugged(4)
  eval((triangle-bugged 4) nil)
  eval-expression((triangle-bugged 4) nil nil 127)
  funcall-interactively(eval-expression (triangle-bugged 4) nil nil 127)
  call-interactively(eval-expression nil nil)
  command-execute(eval-expression)
---------- Buffer: *Backtrace* ----------

(I have reformatted this example slightly; the debugger does not fold long lines. As usual, you can quit the debugger by typing q in the *Backtrace* buffer.)

In practice, for a bug as simple as this, the Lisp error line will tell you what you need to know to correct the definition. The function 1= is void.

However, suppose you are not quite certain what is going on? You can read the complete backtrace.

Emacs automatically starts the debugger that puts you in the *Backtrace* buffer. You can also start the debugger manually as described below.

Read the *Backtrace* buffer from the bottom up; it tells you what Emacs did that led to the error. Emacs made an interactive call to C-x C-e (eval-last-sexp), which led to the evaluation of the triangle-bugged expression. Each line above tells you what the Lisp interpreter evaluated next.

The third line from the top of the buffer is

(setq number (1= number))

Emacs tried to evaluate this expression; in order to do so, it tried to evaluate the inner expression shown on the second line from the top:

(1= number)

This is where the error occurred; as the top line says:

Debugger entered--Lisp error: (void-function 1=)

You can correct the mistake, re-evaluate the function definition, and then run your test again.