Initial Commit
[packages] / xemacs-packages / edebug / edebug.el
1 ;;; edebug.el --- a source-level debugger for Emacs Lisp
2
3 ;; Copyright (C) 1988,89,90,91,92,93,94,95,97,1999,2000,01,03,2004
4 ;;       Free Software Foundation, Inc.
5
6 ;; Author: Daniel LaLiberte <liberte@holonexus.org>
7 ;; Maintainer: FSF
8 ;; Keywords: lisp, tools, maint
9
10 ;; This file is part of XEmacs.
11
12 ;; XEmacs is free software; you can redistribute it and/or modify it
13 ;; under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; any later version.
16
17 ;; XEmacs is distributed in the hope that it will be useful, but
18 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20 ;; General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with XEmacs; see the file COPYING.  If not, write to the Free
24 ;; Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
25 ;; 02111-1307, USA.
26
27 ;;; Synched up with: FSF 21.3 + CVS as of 30 June 2004.
28
29 ;;; Commentary:
30
31 ;; This minor mode allows programmers to step through Emacs Lisp
32 ;; source code while executing functions.  You can also set
33 ;; breakpoints, trace (stopping at each expression), evaluate
34 ;; expressions as if outside Edebug, reevaluate and display a list of
35 ;; expressions, trap errors normally caught by debug, and display a
36 ;; debug style backtrace.
37
38 ;;; Minimal Instructions
39 ;; =====================
40
41 ;; First evaluate a defun with C-M-x, then run the function.  Step
42 ;; through the code with SPC, mark breakpoints with b, go until a
43 ;; breakpoint is reached with g, and quit execution with q.  Use the
44 ;; "?" command in edebug to describe other commands.
45 ;; See the Emacs Lisp Reference Manual for more details.
46
47 ;; If you wish to change the default edebug global command prefix, change:
48 ;; (setq edebug-global-prefix "\C-xX")
49
50 ;; Edebug was written by
51 ;; Daniel LaLiberte
52 ;; GTE Labs
53 ;; 40 Sylvan Rd
54 ;; Waltham, MA  02254
55 ;; liberte@holonexus.org
56
57 ;;; Code:
58
59 ;;; Bug reporting
60
61 (defalias 'edebug-submit-bug-report 'report-emacs-bug)
62
63 ;;; Options
64
65 (defgroup edebug nil
66   "A source-level debugger for Emacs Lisp"
67   :group 'lisp)
68
69
70 (defcustom edebug-setup-hook nil
71   "*Functions to call before edebug is used.
72 Each time it is set to a new value, Edebug will call those functions
73 once and then `edebug-setup-hook' is reset to nil.  You could use this
74 to load up Edebug specifications associated with a package you are
75 using but only when you also use Edebug."
76   :type 'hook
77   :group 'edebug)
78
79 ;; edebug-all-defs and edebug-all-forms need to be autoloaded
80 ;; because the byte compiler binds them; as a result, if edebug
81 ;; is first loaded for a require in a compilation, they will be left unbound.
82
83 ;;;###autoload
84 (defcustom edebug-all-defs nil
85   "*If non-nil, evaluation of any defining forms will instrument for Edebug.
86 This applies to `eval-defun', `eval-region', `eval-buffer', and
87 `eval-current-buffer'.  `eval-region' is also called by
88 `eval-last-sexp', and `eval-print-last-sexp'.
89
90 You can use the command `edebug-all-defs' to toggle the value of this
91 variable.  You may wish to make it local to each buffer with
92 \(make-local-variable 'edebug-all-defs) in your
93 `emacs-lisp-mode-hook'."
94   :type 'boolean
95   :group 'edebug)
96
97 ;; edebug-all-defs and edebug-all-forms need to be autoloaded
98 ;; because the byte compiler binds them; as a result, if edebug
99 ;; is first loaded for a require in a compilation, they will be left unbound.
100
101 ;;;###autoload
102 (defcustom edebug-all-forms nil
103   "*Non-nil evaluation of all forms will instrument for Edebug.
104 This doesn't apply to loading or evaluations in the minibuffer.
105 Use the command `edebug-all-forms' to toggle the value of this option."
106   :type 'boolean
107   :group 'edebug)
108
109 (defcustom edebug-eval-macro-args nil
110   "*Non-nil means all macro call arguments may be evaluated.
111 If this variable is nil, the default, Edebug will *not* wrap
112 macro call arguments as if they will be evaluated.
113 For each macro, a `edebug-form-spec' overrides this option.
114 So to specify exceptions for macros that have some arguments evaluated
115 and some not, you should specify an `edebug-form-spec'."
116   :type 'boolean
117   :group 'edebug)
118
119 (defcustom edebug-save-windows t
120   "*If non-nil, Edebug saves and restores the window configuration.
121 That takes some time, so if your program does not care what happens to
122 the window configurations, it is better to set this variable to nil.
123
124 If the value is a list, only the listed windows are saved and
125 restored.
126
127 `edebug-toggle-save-windows' may be used to change this variable."
128   :type '(choice boolean (repeat string))
129   :group 'edebug)
130
131 (defcustom edebug-save-displayed-buffer-points nil
132   "*If non-nil, save and restore point in all displayed buffers.
133
134 Saving and restoring point in other buffers is necessary if you are
135 debugging code that changes the point of a buffer which is displayed
136 in a non-selected window.  If Edebug or the user then selects the
137 window, the buffer's point will be changed to the window's point.
138
139 Saving and restoring point in all buffers is expensive, since it
140 requires selecting each window twice, so enable this only if you need
141 it."
142   :type 'boolean
143   :group 'edebug)
144
145 (defcustom edebug-initial-mode 'step
146   "*Initial execution mode for Edebug, if non-nil.  If this variable
147 is non-@code{nil}, it specifies the initial execution mode for Edebug
148 when it is first activated.  Possible values are step, next, go,
149 Go-nonstop, trace, Trace-fast, continue, and Continue-fast."
150   :type '(choice (const step) (const next) (const go)
151                  (const Go-nonstop) (const trace)
152                  (const Trace-fast) (const continue)
153                  (const Continue-fast))
154   :group 'edebug)
155
156 (defcustom edebug-trace nil
157   "*Non-nil means display a trace of function entry and exit.
158 Tracing output is displayed in a buffer named `*edebug-trace*', one
159 function entry or exit per line, indented by the recursion level.
160
161 You can customize by replacing functions `edebug-print-trace-before'
162 and `edebug-print-trace-after'."
163   :type 'boolean
164   :group 'edebug)
165
166 (defcustom edebug-test-coverage nil
167   "*If non-nil, Edebug tests coverage of all expressions debugged.
168 This is done by comparing the result of each expression
169 with the previous result. Coverage is considered OK if two different
170 results are found.
171
172 Use `edebug-display-freq-count' to display the frequency count and
173 coverage information for a definition."
174   :type 'boolean
175   :group 'edebug)
176
177 (defcustom edebug-continue-kbd-macro nil
178   "*If non-nil, continue defining or executing any keyboard macro.
179 Use this with caution since it is not debugged."
180   :type 'boolean
181   :group 'edebug)
182
183
184 (defcustom edebug-print-length 50
185   "*Default value of `print-length' to use while printing results in Edebug."
186   :type 'integer
187   :group 'edebug)
188 (defcustom edebug-print-level 50
189   "*Default value of `print-level' to use while printing results in Edebug."
190   :type 'integer
191   :group 'edebug)
192 (defcustom edebug-print-circle t
193   "*Default value of `print-circle' to use while printing results in Edebug."
194   :type 'boolean
195   :group 'edebug)
196
197 (defcustom edebug-unwrap-results nil
198   "*Non-nil if Edebug should unwrap results of expressions.
199 This is useful when debugging macros where the results of expressions
200 are instrumented expressions.  But don't do this when results might be
201 circular or an infinite loop will result."
202   :type 'boolean
203   :group 'edebug)
204
205 (defcustom edebug-on-error t
206   "*Value bound to `debug-on-error' while Edebug is active.
207
208 If `debug-on-error' is non-nil, that value is still used.
209
210 If the value is a list of signal names, Edebug will stop when any of
211 these errors are signaled from Lisp code whether or not the signal is
212 handled by a `condition-case'.  This option is useful for debugging
213 signals that *are* handled since they would otherwise be missed.
214 After execution is resumed, the error is signaled again."
215   :type '(choice (const :tag "off")
216                  (repeat :menu-tag "When"
217                          :value (nil)
218                          (symbol :format "%v"))
219                  (const :tag "always" t))
220   :group 'edebug)
221
222 (defcustom edebug-on-quit t
223   "*Value bound to `debug-on-quit' while Edebug is active."
224   :type 'boolean
225   :group 'edebug)
226
227 (defcustom edebug-global-break-condition nil
228   "*If non-nil, an expression to test for at every stop point.
229 If the result is non-nil, then break.  Errors are ignored."
230   :type 'sexp
231   :group 'edebug)
232
233 (defcustom edebug-sit-for-seconds 1
234   "*Number of seconds to pause when execution mode is `trace'."
235   :type 'number
236   :group 'edebug)
237
238 ;;; Form spec utilities.
239
240 ;;;###autoload
241 (defmacro def-edebug-spec (symbol spec)
242   "Set the `edebug-form-spec' property of SYMBOL according to SPEC.
243 Both SYMBOL and SPEC are unevaluated. The SPEC can be 0, t, a symbol
244 \(naming a function), or a list."
245   `(put (quote ,symbol) 'edebug-form-spec (quote ,spec)))
246
247 (defmacro def-edebug-form-spec (symbol spec-form)
248   "For compatibility with old version.  Use `def-edebug-spec' instead."
249   (message "Obsolete: use def-edebug-spec instead.")
250   (def-edebug-spec symbol (eval spec-form)))
251
252 (defun get-edebug-spec (symbol)
253   ;; Get the spec of symbol resolving all indirection.
254   (let ((edebug-form-spec (get symbol 'edebug-form-spec))
255         indirect)
256     (while (and (symbolp edebug-form-spec)
257                 (setq indirect (get edebug-form-spec 'edebug-form-spec)))
258       ;; (edebug-trace "indirection: %s" edebug-form-spec)
259       (setq edebug-form-spec indirect))
260     edebug-form-spec
261     ))
262
263 ;;; Utilities
264
265 ;; Define edebug-gensym - from old cl.el
266 (defvar edebug-gensym-index 0
267   "Integer used by `edebug-gensym' to produce new names.")
268
269 (defun edebug-gensym (&optional prefix)
270   "Generate a fresh uninterned symbol.
271 There is an  optional argument, PREFIX.  PREFIX is the
272 string that begins the new name. Most people take just the default,
273 except when debugging needs suggest otherwise."
274   (if (null prefix)
275       (setq prefix "G"))
276   (let ((newsymbol nil)
277         (newname   ""))
278     (while (not newsymbol)
279       (setq newname (concat prefix (int-to-string edebug-gensym-index)))
280       (setq edebug-gensym-index (+ edebug-gensym-index 1))
281       (if (not (intern-soft newname))
282           (setq newsymbol (make-symbol newname))))
283     newsymbol))
284
285 (defun edebug-lambda-list-keywordp (object)
286   "Return t if OBJECT is a lambda list keyword.
287 A lambda list keyword is a symbol that starts with `&'."
288   (and (symbolp object)
289        (= ?& (aref (symbol-name object) 0))))
290
291
292 (defun edebug-last-sexp ()
293   ;; Return the last sexp before point in current buffer.
294   ;; Assumes Emacs Lisp syntax is active.
295   (car
296    (read-from-string
297     (buffer-substring
298      (save-excursion
299        (forward-sexp -1)
300        (point))
301      (point)))))
302
303 (defun edebug-window-list ()
304   "Return a list of windows, in order of `next-window'."
305   ;; This doesn't work for epoch.
306   (let (window-list)
307     (walk-windows (lambda (w) (push w window-list)))
308     (nreverse window-list)))
309
310 ;; Not used.
311 '(defun edebug-two-window-p ()
312   "Return t if there are two windows."
313   (and (not (one-window-p))
314        (eq (selected-window)
315            (next-window (next-window (selected-window))))))
316
317 (defsubst edebug-lookup-function (object)
318   (while (and (symbolp object) (fboundp object))
319     (setq object (symbol-function object)))
320   object)
321
322 (defun edebug-macrop (object)
323   "Return the macro named by OBJECT, or nil if it is not a macro."
324   (setq object (edebug-lookup-function object))
325   (if (and (listp object)
326            (eq 'macro (car object))
327            (functionp (cdr object)))
328       object))
329
330 (defun edebug-sort-alist (alist function)
331   ;; Return the ALIST sorted with comparison function FUNCTION.
332   ;; This uses 'sort so the sorting is destructive.
333   (sort alist (function
334                (lambda (e1 e2)
335                  (funcall function (car e1) (car e2))))))
336
337 ;;(def-edebug-spec edebug-save-restriction t)
338
339 ;; Not used.  If it is used, def-edebug-spec must be defined before use.
340 '(defmacro edebug-save-restriction (&rest body)
341   "Evaluate BODY while saving the current buffers restriction.
342 BODY may change buffer outside of current restriction, unlike
343 save-restriction.  BODY may change the current buffer,
344 and the restriction will be restored to the original buffer,
345 and the current buffer remains current.
346 Return the result of the last expression in BODY."
347   `(let ((edebug:s-r-beg (point-min-marker))
348          (edebug:s-r-end (point-max-marker)))
349      (unwind-protect
350          (progn ,@body)
351        (save-excursion
352          (set-buffer (marker-buffer edebug:s-r-beg))
353          (narrow-to-region edebug:s-r-beg edebug:s-r-end)))))
354
355 ;;; Display
356
357 (defconst edebug-trace-buffer "*edebug-trace*"
358   "Name of the buffer to put trace info in.")
359
360 (defun edebug-pop-to-buffer (buffer &optional window)
361   ;; Like pop-to-buffer, but select window where BUFFER was last shown.
362   ;; Select WINDOW if it provided and it still exists.  Otherwise,
363   ;; if buffer is currently shown in several windows, choose one.
364   ;; Otherwise, find a new window, possibly splitting one.
365   (setq window (if (and (windowp window) (edebug-window-live-p window)
366                         (eq (window-buffer window) buffer))
367                    window
368                  (if (eq (window-buffer (selected-window)) buffer)
369                      (selected-window)
370                    (edebug-get-buffer-window buffer))))
371   (if window
372       (select-window window)
373     (if (one-window-p)
374         (split-window))
375     ;;      (message "next window: %s" (next-window)) (sit-for 1)
376     (if (eq (get-buffer-window edebug-trace-buffer) (next-window))
377         ;; Don't select trace window
378         nil
379       (select-window (next-window))))
380   (set-window-buffer (selected-window) buffer)
381   (set-window-hscroll (selected-window) 0);; should this be??
382   ;; Selecting the window does not set the buffer until command loop.
383   ;;(set-buffer buffer)
384   )
385
386
387 (defun edebug-get-displayed-buffer-points ()
388   ;; Return a list of buffer point pairs, for all displayed buffers.
389   (let (list)
390     (walk-windows (lambda (w)
391                     (unless (eq w (selected-window))
392                       (push (cons (window-buffer w)
393                                   (window-point w))
394                             list))))
395     list))
396
397
398 (defun edebug-set-buffer-points (buffer-points)
399   ;; Restore the buffer-points created by edebug-get-displayed-buffer-points.
400   (save-current-buffer
401     (mapcar #'(lambda (buf-point)
402                 (when (buffer-live-p (car buf-point)) ; still exists
403                   (set-buffer (car buf-point))
404                   (goto-char (cdr buf-point))))
405             buffer-points)))
406
407 (defun edebug-current-windows (which-windows)
408   ;; Get either a full window configuration or some window information.
409   (if (listp which-windows)
410       (mapcar (function (lambda (window)
411                           (if (edebug-window-live-p window)
412                               (list window
413                                     (window-buffer window)
414                                     (window-point window)
415                                     (window-start window)
416                                     (window-hscroll window)))))
417               which-windows)
418     (current-window-configuration)))
419
420 (defun edebug-set-windows (window-info)
421   ;; Set either a full window configuration or some window information.
422   (if (listp window-info)
423       (mapcar (function
424                (lambda (one-window-info)
425                  (if one-window-info
426                      (apply (function
427                              (lambda (window buffer point start hscroll)
428                                (if (edebug-window-live-p window)
429                                    (progn
430                                      (set-window-buffer window buffer)
431                                      (set-window-point window point)
432                                      (set-window-start window start)
433                                      (set-window-hscroll window hscroll)))))
434                             one-window-info))))
435               window-info)
436     (set-window-configuration window-info)))
437
438 (defalias 'edebug-get-buffer-window 'get-buffer-window)
439 (defalias 'edebug-sit-for 'sit-for)
440 (defalias 'edebug-input-pending-p 'input-pending-p)
441
442
443 ;;; Redefine read and eval functions
444 ;; read is redefined to maybe instrument forms.
445 ;; eval-defun is redefined to check edebug-all-forms and edebug-all-defs.
446
447 ;; Save the original read function
448 (or (fboundp 'edebug-original-read)
449     (defalias 'edebug-original-read  (symbol-function 'read)))
450
451 (defun edebug-read (&optional stream)
452   "Read one Lisp expression as text from STREAM, return as Lisp object.
453 If STREAM is nil, use the value of `standard-input' (which see).
454 STREAM or the value of `standard-input' may be:
455  a buffer (read from point and advance it)
456  a marker (read from where it points and advance it)
457  a function (call it with no arguments for each character,
458      call it with a char as argument to push a char back)
459  a string (takes text from string, starting at the beginning)
460  t (read text line using minibuffer and use it).
461
462 This version, from Edebug, maybe instruments the expression. But the
463 STREAM must be the current buffer to do so.  Whether it instruments is
464 also dependent on the values of `edebug-all-defs' and
465 `edebug-all-forms'."
466   (or stream (setq stream standard-input))
467   (if (eq stream (current-buffer))
468       (edebug-read-and-maybe-wrap-form)
469     (edebug-original-read stream)))
470
471 (or (fboundp 'edebug-original-eval-defun)
472     (defalias 'edebug-original-eval-defun (symbol-function 'eval-defun)))
473
474 ;; We should somehow arrange to be able to do this
475 ;; without actually replacing the eval-defun command.
476 (defun edebug-eval-defun (edebug-it)
477   "Evaluate the top-level form containing point, or after point.
478
479 If the current defun is actually a call to `defvar', then reset the
480 variable using its initial value expression even if the variable
481 already has some other value.  (Normally `defvar' does not change the
482 variable's value if it already has a value.)  Treat `defcustom'
483 similarly.  Reinitialize the face according to `defface' specification.
484
485 With a prefix argument, instrument the code for Edebug.
486
487 Setting `edebug-all-defs' to a non-nil value reverses the meaning of
488 the prefix argument.  Code is then instrumented when this function is
489 invoked without a prefix argument
490
491 If acting on a `defun' for FUNCTION, and the function was
492 instrumented, `Edebug: FUNCTION' is printed in the minibuffer.  If not
493 instrumented, just FUNCTION is printed.
494
495 If not acting on a `defun', the result of evaluation is displayed in
496 the minibuffer."
497   (interactive "P")
498   (let* ((edebugging (not (eq (not edebug-it) (not edebug-all-defs))))
499          (edebug-result)
500          (form
501           (let ((edebug-all-forms edebugging)
502                 (edebug-all-defs (eq edebug-all-defs (not edebug-it))))
503             (edebug-read-top-level-form))))
504     ;; This should be consistent with `eval-defun-1', but not the
505     ;; same, since that gets a macroexpanded form.
506     (cond ((and (eq (car form) 'defvar)
507                 (cdr-safe (cdr-safe form)))
508            ;; Force variable to be bound.
509            (makunbound (nth 1 form)))
510           ((and (eq (car form) 'defcustom)
511                 (default-boundp (nth 1 form)))
512            ;; Force variable to be bound.
513            (set-default (nth 1 form) (eval (nth 2 form))))
514           ((eq (car form) 'defface)
515            ;; Reset the face.
516            (put (nth 1 form) 'face-defface-spec nil)
517            (setq face-new-frame-defaults
518                  (assq-delete-all (nth 1 form) face-new-frame-defaults))))
519     (setq edebug-result (eval form))
520     (if (not edebugging)
521         (princ edebug-result)
522       edebug-result)))
523
524
525 ;;;###autoload
526 (defalias 'edebug-defun 'edebug-eval-top-level-form)
527
528 ;;;###autoload
529 (defun edebug-eval-top-level-form ()
530   "Evaluate the top level form point is in, stepping through with Edebug.
531 This is like `eval-defun' except that it steps the code for Edebug
532 before evaluating it.  It displays the value in the echo area
533 using `eval-expression' (which see).
534
535 If you do this on a function definition
536 such as a defun or defmacro, it defines the function and instruments
537 its definition for Edebug, so it will do Edebug stepping when called
538 later.  It displays `Edebug: FUNCTION' in the echo area to indicate
539 that FUNCTION is now instrumented for Edebug.
540
541 If the current defun is actually a call to `defvar' or `defcustom',
542 evaluating it this way resets the variable using its initial value
543 expression even if the variable already has some other value.
544 \(Normally `defvar' and `defcustom' do not alter the value if there
545 already is one.)"
546   (interactive)
547   (eval-expression
548    ;; Bind edebug-all-forms only while reading, not while evalling
549    ;; but this causes problems while edebugging edebug.
550    (let ((edebug-all-forms t)
551          (edebug-all-defs t))
552      (edebug-read-top-level-form))))
553
554
555 (defun edebug-read-top-level-form ()
556   (let ((starting-point (point)))
557     (end-of-defun)
558     (beginning-of-defun)
559     (prog1
560         (edebug-read-and-maybe-wrap-form)
561       ;; Recover point, but only if no error occurred.
562       (goto-char starting-point))))
563
564
565 ;; Compatibility with old versions.
566 (defalias 'edebug-all-defuns 'edebug-all-defs)
567
568 (defun edebug-all-defs ()
569   "Toggle edebugging of all definitions."
570   (interactive)
571   (setq edebug-all-defs (not edebug-all-defs))
572   (message "Edebugging all definitions is %s."
573            (if edebug-all-defs "on" "off")))
574
575
576 (defun edebug-all-forms ()
577   "Toggle edebugging of all forms."
578   (interactive)
579   (setq edebug-all-forms (not edebug-all-forms))
580   (message "Edebugging all forms is %s."
581            (if edebug-all-forms "on" "off")))
582
583
584 (defun edebug-install-read-eval-functions ()
585   (interactive)
586   ;; Don't install if already installed.
587   (unless load-read-function
588     (setq load-read-function 'edebug-read)
589     (defalias 'eval-defun 'edebug-eval-defun)))
590
591 (defun edebug-uninstall-read-eval-functions ()
592   (interactive)
593   (setq load-read-function nil)
594   (defalias 'eval-defun (symbol-function 'edebug-original-eval-defun)))
595
596
597 ;;; Edebug internal data
598
599 ;; The internal data that is needed for edebugging is kept in the
600 ;; buffer-local variable `edebug-form-data'.
601
602 (make-variable-buffer-local 'edebug-form-data)
603
604 (defvar edebug-form-data nil)
605 ;; A list of entries associating symbols with buffer regions.
606 ;; This is an automatic buffer local variable.  Each entry looks like:
607 ;; @code{(@var{symbol} @var{begin-marker} @var{end-marker}).  The markers
608 ;; are at the beginning and end of an entry level form and @var{symbol} is
609 ;; a symbol that holds all edebug related information for the form on its
610 ;; property list.
611
612 ;; In the future, the symbol will be irrelevant and edebug data will
613 ;; be stored in the definitions themselves rather than in the property
614 ;; list of a symbol.
615
616 (defun edebug-make-form-data-entry (symbol begin end)
617   (list symbol begin end))
618
619 (defsubst edebug-form-data-name (entry)
620   (car entry))
621
622 (defsubst edebug-form-data-begin (entry)
623   (nth 1 entry))
624
625 (defsubst edebug-form-data-end (entry)
626   (nth 2 entry))
627
628 (defsubst edebug-set-form-data-entry (entry name begin end)
629   (setcar entry name);; in case name is changed
630   (set-marker (nth 1 entry) begin)
631   (set-marker (nth 2 entry) end))
632
633 (defun edebug-get-form-data-entry (pnt &optional end-point)
634   ;; Find the edebug form data entry which is closest to PNT.
635   ;; If END-POINT is supplied, match must be exact.
636   ;; Return `nil' if none found.
637   (let ((rest edebug-form-data)
638         closest-entry
639         (closest-dist 999999))  ;; need maxint here
640     (while (and rest (< 0 closest-dist))
641       (let* ((entry (car rest))
642              (begin (edebug-form-data-begin entry))
643              (dist (- pnt begin)))
644         (setq rest (cdr rest))
645         (if (and (<= 0 dist)
646                  (< dist closest-dist)
647                  (or (not end-point)
648                      (= end-point (edebug-form-data-end entry)))
649                  (<= pnt (edebug-form-data-end entry)))
650             (setq closest-dist dist
651                   closest-entry entry))))
652     closest-entry))
653
654 ;; Also need to find all contained entries,
655 ;; and find an entry given a symbol, which should be just assq.
656
657 (defun edebug-form-data-symbol ()
658 ;; Return the edebug data symbol of the form where point is in.
659 ;; If point is not inside a edebuggable form, cause error.
660   (or (edebug-form-data-name (edebug-get-form-data-entry (point)))
661       (error "Not inside instrumented form")))
662
663 (defun edebug-make-top-form-data-entry (new-entry)
664   ;; Make NEW-ENTRY the first element in the `edebug-form-data' list.
665   (edebug-clear-form-data-entry new-entry)
666   (setq edebug-form-data (cons new-entry edebug-form-data)))
667
668 (defun edebug-clear-form-data-entry (entry)
669 ;; If non-nil, clear ENTRY out of the form data.
670 ;; Maybe clear the markers and delete the symbol's edebug property?
671   (if entry
672       (progn
673         ;; Instead of this, we could just find all contained forms.
674         ;; (put (car entry) 'edebug nil)   ;
675         ;; (mapcar 'edebug-clear-form-data-entry   ; dangerous
676         ;;   (get (car entry) 'edebug-dependents))
677         ;; (set-marker (nth 1 entry) nil)
678         ;; (set-marker (nth 2 entry) nil)
679         (setq edebug-form-data (delq entry edebug-form-data)))))
680
681 ;;; Parser utilities
682
683 (defun edebug-syntax-error (&rest args)
684   ;; Signal an invalid-read-syntax with ARGS.
685   (signal 'invalid-read-syntax args))
686
687
688 (defconst edebug-read-syntax-table
689   ;; Lookup table for significant characters indicating the class of the
690   ;; token that follows.  This is not a \"real\" syntax table.
691   ;; XEmacs change: do not use make-char-table
692   (let ((table (make-vector 256 'symbol))
693         (i 0))
694     (while (< i ?!)
695       (aset table i 'space)
696       (setq i (1+ i)))
697     (aset table ?\( 'lparen)
698     (aset table ?\) 'rparen)
699     (aset table ?\' 'quote)
700     (aset table ?\` 'backquote)
701     (aset table ?\, 'comma)
702     (aset table ?\" 'string)
703     (aset table ?\? 'char)
704     (aset table ?\[ 'lbracket)
705     (aset table ?\] 'rbracket)
706     (aset table ?\. 'dot)
707     (aset table ?\# 'hash)
708     ;; We treat numbers as symbols, because of confusion with -, -1, and 1-.
709     ;; We don't care about any other chars since they won't be seen.
710     table))
711
712 (defun edebug-next-token-class ()
713   ;; Move to the next token and return its class.  We only care about
714   ;; lparen, rparen, dot, quote, backquote, comma, string, char, vector,
715   ;; or symbol.
716   (edebug-skip-whitespace)
717   ;; XEmacs change: Also check for vector overflow
718   (if (or (> (char-after) 255)
719           (and (eq (char-after) ?.)
720                (save-excursion
721                  (char-after 1)
722                  (and (>= (char-after) ?0)
723                       (<= (char-after) ?9)))))
724       'symbol
725     (aref edebug-read-syntax-table (char-after))))
726
727
728 (defun edebug-skip-whitespace ()
729   ;; Leave point before the next token, skipping white space and comments.
730   (skip-chars-forward " \t\r\n\f")
731   (while (= (char-after) ?\;)
732     ;; \r is counted as a comment terminator to support selective display.
733     (skip-chars-forward "^\n\r")  ; skip the comment
734     (skip-chars-forward " \t\r\n\f")))
735
736
737 ;; Mostly obsolete reader; still used in one case.
738
739 (defun edebug-read-sexp ()
740   ;; Read one sexp from the current buffer starting at point.
741   ;; Leave point immediately after it.  A sexp can be a list or atom.
742   ;; An atom is a symbol (or number), character, string, or vector.
743   ;; This works for reading anything legitimate, but it
744   ;; is gummed up by parser inconsistencies (bugs?)
745   (let ((class (edebug-next-token-class)))
746     (cond
747      ;; read goes one too far if a (possibly quoted) string or symbol
748      ;; is immediately followed by non-whitespace.
749      ((eq class 'symbol) (edebug-original-read (current-buffer)))
750      ((eq class 'string) (edebug-original-read (current-buffer)))
751      ((eq class 'quote) (forward-char 1)
752       (list 'quote (edebug-read-sexp)))
753      ((eq class 'backquote)
754       (list '\` (edebug-read-sexp)))
755      ((eq class 'comma)
756       (list '\, (edebug-read-sexp)))
757      (t ; anything else, just read it.
758       (edebug-original-read (current-buffer))))))
759
760 ;;; Offsets for reader
761
762 ;; Define a structure to represent offset positions of expressions.
763 ;; Each offset structure looks like: (before . after) for constituents,
764 ;; or for structures that have elements: (before <subexpressions> . after)
765 ;; where the <subexpressions> are the offset structures for subexpressions
766 ;; including the head of a list.
767 (defvar edebug-offsets nil)
768
769 ;; Stack of offset structures in reverse order of the nesting.
770 ;; This is used to get back to previous levels.
771 (defvar edebug-offsets-stack nil)
772 (defvar edebug-current-offset nil) ; Top of the stack, for convenience.
773
774 ;; We must store whether we just read a list with a dotted form that
775 ;; is itself a list.  This structure will be condensed, so the offsets
776 ;; must also be condensed.
777 (defvar edebug-read-dotted-list nil)
778
779 (defsubst edebug-initialize-offsets ()
780   ;; Reinitialize offset recording.
781   (setq edebug-current-offset nil))
782
783 (defun edebug-store-before-offset (point)
784   ;; Add a new offset pair with POINT as the before offset.
785   (let ((new-offset (list point)))
786     (if edebug-current-offset
787         (setcdr edebug-current-offset
788                 (cons new-offset (cdr edebug-current-offset)))
789       ;; Otherwise, we are at the top level, so initialize.
790       (setq edebug-offsets new-offset
791             edebug-offsets-stack nil
792             edebug-read-dotted-list nil))
793     ;; Cons the new offset to the front of the stack.
794     (setq edebug-offsets-stack (cons new-offset edebug-offsets-stack)
795           edebug-current-offset new-offset)
796     ))
797
798 (defun edebug-store-after-offset (point)
799   ;; Finalize the current offset struct by reversing it and
800   ;; store POINT as the after offset.
801   (if (not edebug-read-dotted-list)
802       ;; Just reverse the offsets of all subexpressions.
803       (setcdr edebug-current-offset (nreverse (cdr edebug-current-offset)))
804
805     ;; We just read a list after a dot, which will be abbreviated out.
806     (setq edebug-read-dotted-list nil)
807     ;; Drop the corresponding offset pair.
808     ;; That is, nconc the reverse of the rest of the offsets
809     ;; with the cdr of last offset.
810     (setcdr edebug-current-offset
811             (nconc (nreverse (cdr (cdr edebug-current-offset)))
812                    (cdr (car (cdr edebug-current-offset))))))
813
814   ;; Now append the point using nconc.
815   (setq edebug-current-offset (nconc edebug-current-offset point))
816   ;; Pop the stack.
817   (setq edebug-offsets-stack (cdr edebug-offsets-stack)
818         edebug-current-offset (car edebug-offsets-stack)))
819
820 (defun edebug-ignore-offset ()
821   ;; Ignore the last created offset pair.
822   (setcdr edebug-current-offset (cdr (cdr edebug-current-offset))))
823
824 ;; XEmacs change: we do not yet support defmacro declarations
825 (def-edebug-spec edebug-storing-offsets (form body))
826 (put 'edebug-storing-offsets 'lisp-indent-function 1)
827
828 (defmacro edebug-storing-offsets (point &rest body)
829   `(unwind-protect
830        (progn
831          (edebug-store-before-offset ,point)
832          ,@body)
833      (edebug-store-after-offset (point))))
834
835
836 ;;; Reader for Emacs Lisp.
837
838 ;; Uses edebug-next-token-class (and edebug-skip-whitespace) above.
839
840 (defconst edebug-read-alist
841   '((symbol . edebug-read-symbol)
842     (lparen . edebug-read-list)
843     (string . edebug-read-string)
844     (quote . edebug-read-quote)
845     (backquote . edebug-read-backquote)
846     (comma . edebug-read-comma)
847     (lbracket . edebug-read-vector)
848     (hash . edebug-read-function)
849     ))
850
851 (defun edebug-read-storing-offsets (stream)
852   (let (edebug-read-dotted-list) ; see edebug-store-after-offset
853     (edebug-storing-offsets (point)
854       (funcall
855        (or (cdr (assq (edebug-next-token-class) edebug-read-alist))
856            ;; anything else, just read it.
857            'edebug-original-read)
858        stream))))
859
860 (defun edebug-read-symbol (stream)
861   (edebug-original-read stream))
862
863 (defun edebug-read-string (stream)
864   (edebug-original-read stream))
865
866 (defun edebug-read-quote (stream)
867   ;; Turn 'thing into (quote thing)
868   (forward-char 1)
869   (list
870    (edebug-storing-offsets (1- (point)) 'quote)
871    (edebug-read-storing-offsets stream)))
872
873 (defvar edebug-read-backquote-level 0
874   "If non-zero, we're in a new-style backquote.
875 It should never be negative.  This controls how we read comma constructs.")
876
877 (defun edebug-read-backquote (stream)
878   ;; Turn `thing into (\` thing)
879   (forward-char 1)
880   (list
881    (edebug-storing-offsets (1- (point)) '\`)
882    (let ((edebug-read-backquote-level (1+ edebug-read-backquote-level)))
883      (edebug-read-storing-offsets stream))))
884
885 (defun edebug-read-comma (stream)
886   ;; Turn ,thing into (\, thing).  Handle ,@ and ,. also.
887   (let ((opoint (point)))
888     (forward-char 1)
889     (let ((symbol '\,))
890       (cond ((eq (char-after) ?\.)
891              (setq symbol '\,\.)
892              (forward-char 1))
893             ((eq (char-after) ?\@)
894              (setq symbol '\,@)
895              (forward-char 1)))
896       ;; Generate the same structure of offsets we would have
897       ;; if the resulting list appeared verbatim in the input text.
898       (if (zerop edebug-read-backquote-level)
899           (edebug-storing-offsets opoint symbol)
900         (list
901          (edebug-storing-offsets opoint symbol)
902          (let ((edebug-read-backquote-level (1- edebug-read-backquote-level)))
903            (edebug-read-storing-offsets stream)))))))
904
905 (defun edebug-read-function (stream)
906   ;; Turn #'thing into (function thing)
907   (forward-char 1)
908   (cond ((eq ?\' (char-after))
909          (forward-char 1)
910          (list
911           (edebug-storing-offsets (- (point) 2)
912             (if (featurep 'cl) 'function* 'function))
913           (edebug-read-storing-offsets stream)))
914         ;; XEmacs: Add #* for bit vectors
915         ;; SXEmacs: Add #r for raw strings
916         ((memq (char-after) '(?: ?B ?O ?X ?b ?o ?x ?1 ?2 ?3 ?4 ?5 ?6
917                               ?7 ?8 ?9 ?0 ?* ?r))
918          (backward-char 1)
919          (edebug-original-read stream))
920         (t (edebug-syntax-error "Bad char after #"))))
921
922 (defun edebug-read-list (stream)
923   (forward-char 1)                      ; skip \(
924   (prog1
925       (let ((elements))
926         (while (not (memq (edebug-next-token-class) '(rparen dot)))
927           (if (and (eq (edebug-next-token-class) 'backquote)
928                    (null elements)
929                    (zerop edebug-read-backquote-level))
930               (progn
931                 ;; Old style backquote.
932                 (forward-char 1)        ; Skip backquote.
933                 ;; Call edebug-storing-offsets here so that we
934                 ;; produce the same offsets we would have had
935                 ;; if the backquote were an ordinary symbol.
936                 (push (edebug-storing-offsets (1- (point)) '\`) elements))
937             (push (edebug-read-storing-offsets stream) elements)))
938         (setq elements (nreverse elements))
939         (if (eq 'dot (edebug-next-token-class))
940             (let (dotted-form)
941               (forward-char 1)          ; skip \.
942               (setq dotted-form (edebug-read-storing-offsets stream))
943                     elements (nconc elements dotted-form)
944               (if (not (eq (edebug-next-token-class) 'rparen))
945                   (edebug-syntax-error "Expected `)'"))
946               (setq edebug-read-dotted-list (listp dotted-form))
947               ))
948         elements)
949     (forward-char 1)                    ; skip \)
950     ))
951
952 (defun edebug-read-vector (stream)
953   (forward-char 1)                      ; skip \[
954   (prog1
955       (let ((elements))
956         (while (not (eq 'rbracket (edebug-next-token-class)))
957           (push (edebug-read-storing-offsets stream) elements))
958         (apply 'vector (nreverse elements)))
959     (forward-char 1)                    ; skip \]
960     ))
961
962 ;;; Cursors for traversal of list and vector elements with offsets.
963
964 (defvar edebug-dotted-spec nil)
965
966 (defun edebug-new-cursor (expressions offsets)
967   ;; Return a new cursor for EXPRESSIONS with OFFSETS.
968   (if (vectorp expressions)
969       (setq expressions (append expressions nil)))
970   (cons expressions offsets))
971
972 (defsubst edebug-set-cursor (cursor expressions offsets)
973   ;; Set the CURSOR's EXPRESSIONS and OFFSETS to the given.
974   ;; Return the cursor.
975   (setcar cursor expressions)
976   (setcdr cursor offsets)
977   cursor)
978
979 (defun edebug-copy-cursor (cursor)
980   ;; Copy the cursor using the same object and offsets.
981   (cons (car cursor) (cdr cursor)))
982
983 (defsubst edebug-cursor-expressions (cursor)
984   (car cursor))
985 (defsubst edebug-cursor-offsets (cursor)
986   (cdr cursor))
987
988 (defsubst edebug-empty-cursor (cursor)
989   ;; Return non-nil if CURSOR is empty - meaning no more elements.
990   (null (car cursor)))
991
992 (defsubst edebug-top-element (cursor)
993   ;; Return the top element at the cursor.
994   ;; Assumes not empty.
995   (car (car cursor)))
996
997 (defun edebug-top-element-required (cursor &rest error)
998   ;; Check if a dotted form is required.
999   (if edebug-dotted-spec (edebug-no-match cursor "Dot expected."))
1000   ;; Check if there is at least one more argument.
1001   (if (edebug-empty-cursor cursor) (apply 'edebug-no-match cursor error))
1002   ;; Return that top element.
1003   (edebug-top-element cursor))
1004
1005 (defsubst edebug-top-offset (cursor)
1006   ;; Return the top offset pair corresponding to the top element.
1007   (car (cdr cursor)))
1008
1009 (defun edebug-move-cursor (cursor)
1010   ;; Advance and return the cursor to the next element and offset.
1011   ;; throw no-match if empty before moving.
1012   ;; This is a violation of the cursor encapsulation, but
1013   ;; there is plenty of that going on while matching.
1014   ;; The following test should always fail.
1015   (if (edebug-empty-cursor cursor)
1016       (edebug-no-match cursor "Not enough arguments."))
1017   (setcar cursor (cdr (car cursor)))
1018   (setcdr cursor (cdr (cdr cursor)))
1019   cursor)
1020
1021
1022 (defun edebug-before-offset (cursor)
1023   ;; Return the before offset of the cursor.
1024   ;; If there is nothing left in the offsets,
1025   ;; return one less than the offset itself,
1026   ;; which is the after offset for a list.
1027   (let ((offset (edebug-cursor-offsets cursor)))
1028     (if (consp offset)
1029         (car (car offset))
1030       (1- offset))))
1031
1032 (defun edebug-after-offset (cursor)
1033   ;; Return the after offset of the cursor object.
1034   (let ((offset (edebug-top-offset cursor)))
1035     (while (consp offset)
1036       (setq offset (cdr offset)))
1037     offset))
1038
1039 ;;; The Parser
1040
1041 ;; The top level function for parsing forms is
1042 ;; edebug-read-and-maybe-wrap-form; it calls all the rest.  It checks the
1043 ;; syntax a bit and leaves point at any error it finds, but otherwise
1044 ;; should appear to work like eval-defun.
1045
1046 ;; The basic plan is to surround each expression with a call to
1047 ;; the edebug debugger together with indexes into a table of positions of
1048 ;; all expressions.  Thus an expression "exp" becomes:
1049
1050 ;; (edebug-after (edebug-before 1) 2 exp)
1051
1052 ;; When this is evaluated, first point is moved to the beginning of
1053 ;; exp at offset 1 of the current function.  The expression is
1054 ;; evaluated, which may cause more edebug calls, and then point is
1055 ;; moved to offset 2 after the end of exp.
1056
1057 ;; The highest level expressions of the function are wrapped in a call to
1058 ;; edebug-enter, which supplies the function name and the actual
1059 ;; arguments to the function.  See functions edebug-enter, edebug-before,
1060 ;; and edebug-after for more details.
1061
1062 ;; Dynamically bound vars, left unbound, but globally declared.
1063 ;; This is to quiet the byte compiler.
1064
1065 ;; Window data of the highest definition being wrapped.
1066 ;; This data is shared by all embedded definitions.
1067 (defvar edebug-top-window-data)
1068
1069 (defvar edebug-&optional)
1070 (defvar edebug-&rest)
1071 (defvar edebug-gate nil) ;; whether no-match forces an error.
1072
1073 (defvar edebug-def-name nil) ; name of definition, used by interactive-form
1074 (defvar edebug-old-def-name nil) ; previous name of containing definition.
1075
1076 (defvar edebug-error-point nil)
1077 (defvar edebug-best-error nil)
1078
1079
1080 (defun edebug-read-and-maybe-wrap-form ()
1081   ;; Read a form and wrap it with edebug calls, if the conditions are right.
1082   ;; Here we just catch any no-match not caught below and signal an error.
1083
1084   ;; Run the setup hook.
1085   ;; If it gets an error, make it nil.
1086   (let ((temp-hook edebug-setup-hook))
1087     (setq edebug-setup-hook nil)
1088     (run-hooks 'temp-hook))
1089
1090   (let (result
1091         edebug-top-window-data
1092         edebug-def-name;; make sure it is locally nil
1093         ;; I don't like these here!!
1094         edebug-&optional
1095         edebug-&rest
1096         edebug-gate
1097         edebug-best-error
1098         edebug-error-point
1099         no-match
1100         ;; Do this once here instead of several times.
1101         (max-lisp-eval-depth (+ 800 max-lisp-eval-depth))
1102         (max-specpdl-size (+ 2000 max-specpdl-size)))
1103     (setq no-match
1104           (catch 'no-match
1105             (setq result (edebug-read-and-maybe-wrap-form1))
1106             nil))
1107     (if no-match
1108         (apply 'edebug-syntax-error no-match))
1109     result))
1110
1111
1112 (defun edebug-read-and-maybe-wrap-form1 ()
1113   (let (spec
1114         def-kind
1115         defining-form-p
1116         def-name
1117         ;; These offset things don't belong here, but to support recursive
1118         ;; calls to edebug-read, they need to be here.
1119         edebug-offsets
1120         edebug-offsets-stack
1121         edebug-current-offset ; reset to nil
1122         )
1123     (save-excursion
1124       (if (and (eq 'lparen (edebug-next-token-class))
1125                (eq 'symbol (progn (forward-char 1) (edebug-next-token-class))))
1126           ;; Find out if this is a defining form from first symbol
1127           (setq def-kind (edebug-original-read (current-buffer))
1128                 spec (and (symbolp def-kind) (get-edebug-spec def-kind))
1129                 defining-form-p (and (listp spec)
1130                                      (eq '&define (car spec)))
1131                 ;; This is incorrect in general!! But OK most of the time.
1132                 def-name (if (and defining-form-p
1133                                   (eq 'name (car (cdr spec)))
1134                                   (eq 'symbol (edebug-next-token-class)))
1135                              (edebug-original-read (current-buffer))))))
1136 ;;;(message "all defs: %s   all forms: %s"  edebug-all-defs edebug-all-forms)
1137     (cond
1138      (defining-form-p
1139        (if (or edebug-all-defs edebug-all-forms)
1140            ;; If it is a defining form and we are edebugging defs,
1141            ;; then let edebug-list-form start it.
1142            (let ((cursor (edebug-new-cursor
1143                           (list (edebug-read-storing-offsets (current-buffer)))
1144                           (list edebug-offsets))))
1145              (car
1146               (edebug-make-form-wrapper
1147                cursor
1148                (edebug-before-offset cursor)
1149                (1- (edebug-after-offset cursor))
1150                (list (cons (symbol-name def-kind) (cdr spec))))))
1151
1152          ;; Not edebugging this form, so reset the symbol's edebug
1153          ;; property to be just a marker at the definition's source code.
1154          ;; This only works for defs with simple names.
1155          (put def-name 'edebug (point-marker))
1156          ;; Also nil out dependent defs.
1157          '(mapcar (function
1158                    (lambda (def)
1159                      (put def-name 'edebug nil)))
1160                   (get def-name 'edebug-dependents))
1161          (edebug-read-sexp)))
1162
1163      ;; If all forms are being edebugged, explicitly wrap it.
1164      (edebug-all-forms
1165       (let ((cursor (edebug-new-cursor
1166                      (list (edebug-read-storing-offsets (current-buffer)))
1167                      (list edebug-offsets))))
1168         (edebug-make-form-wrapper
1169          cursor
1170          (edebug-before-offset cursor)
1171          (edebug-after-offset cursor)
1172          nil)))
1173
1174      ;; Not a defining form, and not edebugging.
1175      (t (edebug-read-sexp)))
1176     ))
1177
1178
1179 (defvar edebug-def-args) ; args of defining form.
1180 (defvar edebug-def-interactive) ; is it an emacs interactive function?
1181 (defvar edebug-inside-func)  ;; whether code is inside function context.
1182 ;; Currently def-form sets this to nil; def-body sets it to t.
1183
1184 (defun edebug-interactive-p-name ()
1185   ;; Return a unique symbol for the variable used to store the
1186   ;; status of interactive-p for this function.
1187   (intern (format "edebug-%s-interactive-p" edebug-def-name)))
1188
1189
1190 (defun edebug-wrap-def-body (forms)
1191   "Wrap the FORMS of a definition body."
1192   (if edebug-def-interactive
1193       `(let ((,(edebug-interactive-p-name)
1194               (interactive-p)))
1195          ,(edebug-make-enter-wrapper forms))
1196     (edebug-make-enter-wrapper forms)))
1197
1198
1199 (defun edebug-make-enter-wrapper (forms)
1200   ;; Generate the enter wrapper for some forms of a definition.
1201   ;; This is not to be used for the body of other forms, e.g. `while',
1202   ;; since it wraps the list of forms with a call to `edebug-enter'.
1203   ;; Uses the dynamically bound vars edebug-def-name and edebug-def-args.
1204   ;; Do this after parsing since that may find a name.
1205   (setq edebug-def-name
1206         (or edebug-def-name edebug-old-def-name (edebug-gensym "edebug-anon")))
1207   `(edebug-enter
1208     (quote ,edebug-def-name)
1209     ,(if edebug-inside-func
1210          `(list
1211            ;; Doesn't work with more than one def-body!!
1212            ;; But the list will just be reversed.
1213            ,@(nreverse edebug-def-args))
1214        'nil)
1215     (function (lambda () ,@forms))
1216     ))
1217
1218
1219 (defvar edebug-form-begin-marker) ; the mark for def being instrumented
1220
1221 (defvar edebug-offset-index) ; the next available offset index.
1222 (defvar edebug-offset-list) ; the list of offset positions.
1223
1224 (defun edebug-inc-offset (offset)
1225   ;; modifies edebug-offset-index and edebug-offset-list
1226   ;; accesses edebug-func-marc and buffer point
1227   (prog1
1228       edebug-offset-index
1229     (setq edebug-offset-list (cons (- offset edebug-form-begin-marker)
1230                                    edebug-offset-list)
1231           edebug-offset-index (1+ edebug-offset-index))))
1232
1233
1234 (defun edebug-make-before-and-after-form (before-index form after-index)
1235   ;; Return the edebug form for the current function at offset BEFORE-INDEX
1236   ;; given FORM.  Looks like:
1237   ;; (edebug-after (edebug-before BEFORE-INDEX) AFTER-INDEX FORM)
1238   ;; Also increment the offset index for subsequent use.
1239   (list 'edebug-after
1240         (list 'edebug-before before-index)
1241         after-index form))
1242
1243 (defun edebug-make-after-form (form after-index)
1244   ;; Like edebug-make-before-and-after-form, but only after.
1245   (list 'edebug-after 0 after-index form))
1246
1247
1248 (defun edebug-unwrap (sexp)
1249   "Return the unwrapped SEXP or return it as is if it is not wrapped.
1250 The SEXP might be the result of wrapping a body, which is a list of
1251 expressions; a `progn' form will be returned enclosing these forms."
1252   (if (consp sexp)
1253       (cond
1254        ((eq 'edebug-after (car sexp))
1255         (nth 3 sexp))
1256        ((eq 'edebug-enter (car sexp))
1257         (let ((forms (nthcdr 2 (nth 1 (nth 3 sexp)))))
1258           (if (> (length forms) 1)
1259               (cons 'progn forms)  ;; could return (values forms) instead.
1260             (car forms))))
1261        (t sexp);; otherwise it is not wrapped, so just return it.
1262        )
1263     sexp))
1264
1265 (defun edebug-unwrap* (sexp)
1266   "Return the sexp recursively unwrapped."
1267   (let ((new-sexp (edebug-unwrap sexp)))
1268     (while (not (eq sexp new-sexp))
1269       (setq sexp new-sexp
1270             new-sexp (edebug-unwrap sexp)))
1271     (if (consp new-sexp)
1272         (mapcar 'edebug-unwrap* new-sexp)
1273       new-sexp)))
1274
1275
1276 (defun edebug-defining-form (cursor form-begin form-end speclist)
1277   ;; Process the defining form, starting outside the form.
1278   ;; The speclist is a generated list spec that looks like:
1279   ;;   (("def-symbol" defining-form-spec-sans-&define))
1280   ;; Skip the first offset.
1281   (edebug-set-cursor cursor (edebug-cursor-expressions cursor)
1282                      (cdr (edebug-cursor-offsets cursor)))
1283   (edebug-make-form-wrapper
1284    cursor
1285    form-begin (1- form-end)
1286    speclist))
1287
1288 (defun edebug-make-form-wrapper (cursor form-begin form-end
1289                                         &optional speclist)
1290   ;; Wrap a form, usually a defining form, but any evaluated one.
1291   ;; If speclist is non-nil, this is being called by edebug-defining-form.
1292   ;; Otherwise it is being called from edebug-read-and-maybe-wrap-form1.
1293   ;; This is a hack, but I havent figured out a simpler way yet.
1294   (let* ((form-data-entry (edebug-get-form-data-entry form-begin form-end))
1295          ;; Set this marker before parsing.
1296          (edebug-form-begin-marker
1297           (if form-data-entry
1298               (edebug-form-data-begin form-data-entry)
1299             ;; Buffer must be current-buffer for this to work:
1300             (set-marker (make-marker) form-begin))))
1301
1302     (let (edebug-offset-list
1303           (edebug-offset-index 0)
1304           result
1305           ;; For definitions.
1306           ;; (edebug-containing-def-name edebug-def-name)
1307           ;; Get name from form-data, if any.
1308           (edebug-old-def-name (edebug-form-data-name form-data-entry))
1309           edebug-def-name
1310           edebug-def-args
1311           edebug-def-interactive
1312           edebug-inside-func;; whether wrapped code executes inside a function.
1313           )
1314
1315       (setq result
1316             (if speclist
1317                 (edebug-match cursor speclist)
1318
1319               ;; else wrap as an enter-form.
1320               (edebug-make-enter-wrapper (list (edebug-form cursor)))))
1321
1322       ;; Set the name here if it was not set by edebug-make-enter-wrapper.
1323       (setq edebug-def-name
1324             (or edebug-def-name edebug-old-def-name (edebug-gensym "edebug-anon")))
1325
1326       ;; Add this def as a dependent of containing def.  Buggy.
1327       '(if (and edebug-containing-def-name
1328                 (not (get edebug-containing-def-name 'edebug-dependents)))
1329            (put edebug-containing-def-name 'edebug-dependents
1330                 (cons edebug-def-name
1331                       (get edebug-containing-def-name
1332                            'edebug-dependents))))
1333
1334       ;; Create a form-data-entry or modify existing entry's markers.
1335       ;; In the latter case, pointers to the entry remain eq.
1336       (if (not form-data-entry)
1337           (setq form-data-entry
1338                 (edebug-make-form-data-entry
1339                  edebug-def-name
1340                  edebug-form-begin-marker
1341                  ;; Buffer must be current-buffer.
1342                  (set-marker (make-marker) form-end)
1343                  ))
1344         (edebug-set-form-data-entry
1345          form-data-entry edebug-def-name ;; in case name is changed
1346          form-begin form-end))
1347
1348       ;;    (message "defining: %s" edebug-def-name) (sit-for 2)
1349       (edebug-make-top-form-data-entry form-data-entry)
1350       (message "Edebug: %s" edebug-def-name)
1351       ;;(debug edebug-def-name)
1352
1353       ;; Destructively reverse edebug-offset-list and make vector from it.
1354       (setq edebug-offset-list (vconcat (nreverse edebug-offset-list)))
1355
1356       ;; Side effects on the property list of edebug-def-name.
1357       (edebug-clear-frequency-count edebug-def-name)
1358       (edebug-clear-coverage edebug-def-name)
1359
1360       ;; Set up the initial window data.
1361       (if (not edebug-top-window-data) ;; if not already set, do it now.
1362           (let ((window ;; Find the best window for this buffer.
1363                  (or (get-buffer-window (current-buffer))
1364                      (selected-window))))
1365             (setq edebug-top-window-data
1366                   (cons window (window-start window)))))
1367
1368       ;; Store the edebug data in symbol's property list.
1369       (put edebug-def-name 'edebug
1370            ;; A struct or vector would be better here!!
1371            (list edebug-form-begin-marker
1372                  nil                    ; clear breakpoints
1373                  edebug-offset-list
1374                  edebug-top-window-data
1375                  ))
1376       result
1377       )))
1378
1379
1380 (defun edebug-clear-frequency-count (name)
1381   ;; Create initial frequency count vector.
1382   ;; For each stop point, the counter is incremented each time it is visited.
1383   (put name 'edebug-freq-count
1384        (make-vector (length edebug-offset-list) 0)))
1385
1386
1387 (defun edebug-clear-coverage (name)
1388   ;; Create initial coverage vector.
1389   ;; Only need one per expression, but it is simpler to use stop points.
1390   (put name 'edebug-coverage
1391        (make-vector (length edebug-offset-list) 'unknown)))
1392
1393
1394 (defun edebug-form (cursor)
1395   ;; Return the instrumented form for the following form.
1396   ;; Add the point offsets to the edebug-offset-list for the form.
1397   (let* ((form (edebug-top-element-required cursor "Expected form"))
1398          (offset (edebug-top-offset cursor)))
1399     (prog1
1400         (cond
1401          ((consp form)
1402           ;; The first offset for a list form is for the list form itself.
1403           (if (eq 'quote (car form))
1404               form
1405             (let* ((head (car form))
1406                    (spec (and (symbolp head) (get-edebug-spec head)))
1407                    (new-cursor (edebug-new-cursor form offset)))
1408               ;; Find out if this is a defining form from first symbol.
1409               ;; An indirect spec would not work here, yet.
1410               (if (and (consp spec) (eq '&define (car spec)))
1411                   (edebug-defining-form
1412                    new-cursor
1413                    (car offset);; before the form
1414                    (edebug-after-offset cursor)
1415                    (cons (symbol-name head) (cdr spec)))
1416                 ;; Wrap a regular form.
1417                 (edebug-make-before-and-after-form
1418                  (edebug-inc-offset (car offset))
1419                  (edebug-list-form new-cursor)
1420                  ;; After processing the list form, the new-cursor is left
1421                  ;; with the offset after the form.
1422                  (edebug-inc-offset (edebug-cursor-offsets new-cursor))))
1423               )))
1424
1425          ((symbolp form)
1426           (cond
1427            ;; Check for constant symbols that don't get wrapped.
1428            ((or (memq form '(t nil))
1429                 (keywordp form))
1430             form)
1431
1432            (t ;; just a variable
1433             (edebug-make-after-form form (edebug-inc-offset (cdr offset))))))
1434
1435          ;; Anything else is self-evaluating.
1436          (t form))
1437     (edebug-move-cursor cursor))))
1438
1439
1440 (defsubst edebug-forms (cursor)  (edebug-match cursor '(&rest form)))
1441 (defsubst edebug-sexps (cursor)  (edebug-match cursor '(&rest sexp)))
1442
1443 (defsubst edebug-list-form-args (head cursor)
1444   ;; Process the arguments of a list form given that head of form is a symbol.
1445   ;; Helper for edebug-list-form
1446   (let ((spec (get-edebug-spec head)))
1447     (cond
1448      (spec
1449       (cond
1450        ((consp spec)
1451         ;; It is a speclist.
1452         (let (edebug-best-error
1453               edebug-error-point);; This may not be needed.
1454           (edebug-match-sublist cursor spec)))
1455        ((eq t spec) (edebug-forms cursor))
1456        ((eq 0 spec) (edebug-sexps cursor))
1457        ((symbolp spec) (funcall spec cursor));; Not used by edebug,
1458                                         ; but leave it in for compatibility.
1459        ))
1460      ;; No edebug-form-spec provided.
1461      ((edebug-macrop head)
1462       (if edebug-eval-macro-args
1463           (edebug-forms cursor)
1464         (edebug-sexps cursor)))
1465      (t ;; Otherwise it is a function call.
1466       (edebug-forms cursor)))))
1467
1468
1469 (defun edebug-list-form (cursor)
1470   ;; Return an instrumented form built from the list form.
1471   ;; The after offset will be left in the cursor after processing the form.
1472   (let ((head (edebug-top-element-required cursor "Expected elements"))
1473         ;; Prevent backtracking whenever instrumenting.
1474         (edebug-gate t)
1475         ;; A list form is never optional because it matches anything.
1476         (edebug-&optional nil)
1477         (edebug-&rest nil))
1478     ;; Skip the first offset.
1479     (edebug-set-cursor cursor (edebug-cursor-expressions cursor)
1480                        (cdr (edebug-cursor-offsets cursor)))
1481     (cond
1482      ((symbolp head)
1483       (cond
1484        ((null head) nil) ; () is legal.
1485        ((eq head 'interactive-p)
1486         ;; Special case: replace (interactive-p) with variable
1487         (setq edebug-def-interactive 'check-it)
1488         (edebug-move-cursor cursor)
1489         (edebug-interactive-p-name))
1490        (t
1491         (cons head (edebug-list-form-args
1492                     head (edebug-move-cursor cursor))))))
1493
1494      ((consp head)
1495       (if (eq (car head) ',)
1496           ;; The head of a form should normally be a symbol or a lambda
1497           ;; expression but it can also be an unquote form to be filled
1498           ;; before evaluation.  We evaluate the arguments anyway, on the
1499           ;; assumption that the unquote form will place a proper function
1500           ;; name (rather than a macro name).
1501           (edebug-match cursor '(("," def-form) body))
1502         ;; Process anonymous function and args.
1503         ;; This assumes no anonymous macros.
1504         (edebug-match-specs cursor '(lambda-expr body) 'edebug-match-specs)))
1505
1506      (t (edebug-syntax-error
1507          "Head of list form must be a symbol or lambda expression")))
1508       ))
1509
1510 ;;; Matching of specs.
1511
1512 (defvar edebug-after-dotted-spec nil)
1513
1514 (defvar edebug-matching-depth 0)  ;; initial value
1515 (defconst edebug-max-depth 150)  ;; maximum number of matching recursions.
1516
1517
1518 ;;; Failure to match
1519
1520 ;; This throws to no-match, if there are higher alternatives.
1521 ;; Otherwise it signals an error.  The place of the error is found
1522 ;; with the two before- and after-offset functions.
1523
1524 (defun edebug-no-match (cursor &rest edebug-args)
1525   ;; Throw a no-match, or signal an error immediately if gate is active.
1526   ;; Remember this point in case we need to report this error.
1527   (setq edebug-error-point (or edebug-error-point
1528                                (edebug-before-offset cursor))
1529         edebug-best-error (or edebug-best-error edebug-args))
1530   (if (and edebug-gate (not edebug-&optional))
1531       (progn
1532         (if edebug-error-point
1533             (goto-char edebug-error-point))
1534         (apply 'edebug-syntax-error edebug-args))
1535     (funcall 'throw 'no-match edebug-args)))
1536
1537
1538 (defun edebug-match (cursor specs)
1539   ;; Top level spec matching function.
1540   ;; Used also at each lower level of specs.
1541   (let (edebug-&optional
1542         edebug-&rest
1543         edebug-best-error
1544         edebug-error-point
1545         (edebug-gate edebug-gate)  ;; locally bound to limit effect
1546         )
1547     (edebug-match-specs cursor specs 'edebug-match-specs)))
1548
1549
1550 (defun edebug-match-one-spec (cursor spec)
1551   ;; Match one spec, which is not a keyword &-spec.
1552   (cond
1553    ((symbolp spec) (edebug-match-symbol cursor spec))
1554    ((vectorp spec) (edebug-match cursor (append spec nil)))
1555    ((stringp spec) (edebug-match-string cursor spec))
1556    ((listp spec) (edebug-match-list cursor spec))
1557    ))
1558
1559
1560 (defun edebug-match-specs (cursor specs remainder-handler)
1561   ;; Append results of matching the list of specs.
1562   ;; The first spec is handled and the remainder-handler handles the rest.
1563   (let ((edebug-matching-depth
1564          (if (> edebug-matching-depth edebug-max-depth)
1565              (error "too deep - perhaps infinite loop in spec?")
1566            (1+ edebug-matching-depth))))
1567     (cond
1568      ((null specs) nil)
1569
1570      ;; Is the spec dotted?
1571      ((atom specs)
1572       (let ((edebug-dotted-spec t));; Containing spec list was dotted.
1573         (edebug-match-specs cursor (list specs) remainder-handler)))
1574
1575      ;; Is the form dotted?
1576      ((not (listp (edebug-cursor-expressions cursor)));; allow nil
1577       (if (not edebug-dotted-spec)
1578           (edebug-no-match cursor "Dotted spec required."))
1579       ;; Cancel dotted spec and dotted form.
1580       (let ((edebug-dotted-spec)
1581             (this-form (edebug-cursor-expressions cursor))
1582             (this-offset (edebug-cursor-offsets cursor)))
1583         ;; Wrap the form in a list, (by changing the cursor??)...
1584         (edebug-set-cursor cursor (list this-form) this-offset)
1585         ;; and process normally, then unwrap the result.
1586         (car (edebug-match-specs cursor specs remainder-handler))))
1587
1588      (t;; Process normally.
1589       (let* ((spec (car specs))
1590              (rest)
1591              (first-char (and (symbolp spec) (aref (symbol-name spec) 0))))
1592         ;;(message "spec = %s  first char = %s" spec first-char) (sit-for 1)
1593         (nconc
1594          (cond
1595           ((eq ?& first-char);; "&" symbols take all following specs.
1596            (funcall (get-edebug-spec spec) cursor (cdr specs)))
1597           ((eq ?: first-char);; ":" symbols take one following spec.
1598            (setq rest (cdr (cdr specs)))
1599            (funcall (get-edebug-spec spec) cursor (car (cdr specs))))
1600           (t;; Any other normal spec.
1601            (setq rest (cdr specs))
1602            (edebug-match-one-spec cursor spec)))
1603          (funcall remainder-handler cursor rest remainder-handler)))))))
1604
1605
1606 ;; Define specs for all the symbol specs with functions used to process them.
1607 ;; Perhaps we shouldn't be doing this with edebug-form-specs since the
1608 ;; user may want to define macros or functions with the same names.
1609 ;; We could use an internal obarray for these primitive specs.
1610
1611 (dolist (pair '((&optional . edebug-match-&optional)
1612                 (&rest . edebug-match-&rest)
1613                 (&or . edebug-match-&or)
1614                 (form . edebug-match-form)
1615                 (sexp . edebug-match-sexp)
1616                 (body . edebug-match-body)
1617                 (&define . edebug-match-&define)
1618                 (name . edebug-match-name)
1619                 (:name . edebug-match-colon-name)
1620                 (arg . edebug-match-arg)
1621                 (def-body . edebug-match-def-body)
1622                 (def-form . edebug-match-def-form)
1623                 ;; Less frequently used:
1624                 ;; (function . edebug-match-function)
1625                 (lambda-expr . edebug-match-lambda-expr)
1626                 (&not . edebug-match-&not)
1627                 (&key . edebug-match-&key)
1628                 (place . edebug-match-place)
1629                 (gate . edebug-match-gate)
1630                 ;;   (nil . edebug-match-nil)  not this one - special case it.
1631                 ))
1632   (put (car pair) 'edebug-form-spec (cdr pair)))
1633
1634 (defun edebug-match-symbol (cursor symbol)
1635   ;; Match a symbol spec.
1636   (let* ((spec (get-edebug-spec symbol)))
1637     (cond
1638      (spec
1639       (if (consp spec)
1640           ;; It is an indirect spec.
1641           (edebug-match cursor spec)
1642         ;; Otherwise it should be the symbol name of a function.
1643         ;; There could be a bug here - maybe need to do edebug-match bindings.
1644         (funcall spec cursor)))
1645
1646      ((null symbol)  ;; special case this.
1647       (edebug-match-nil cursor))
1648
1649      ((fboundp symbol)                  ; is it a predicate?
1650       (let ((sexp (edebug-top-element-required cursor "Expected" symbol)))
1651         ;; Special case for edebug-`.
1652         (if (and (listp sexp) (eq (car sexp) ',))
1653             (edebug-match cursor '(("," def-form)))
1654           (if (not (funcall symbol sexp))
1655               (edebug-no-match cursor symbol "failed"))
1656           (edebug-move-cursor cursor)
1657           (list sexp))))
1658      (t (error "%s is not a form-spec or function" symbol))
1659      )))
1660
1661
1662 (defun edebug-match-sexp (cursor)
1663   (list (prog1 (edebug-top-element-required cursor "Expected sexp")
1664           (edebug-move-cursor cursor))))
1665
1666 (defun edebug-match-form (cursor)
1667   (list (edebug-form cursor)))
1668
1669 (defalias 'edebug-match-place 'edebug-match-form)
1670   ;; Currently identical to edebug-match-form.
1671   ;; This is for common lisp setf-style place arguments.
1672
1673 (defsubst edebug-match-body (cursor) (edebug-forms cursor))
1674
1675 (defun edebug-match-&optional (cursor specs)
1676   ;; Keep matching until one spec fails.
1677   (edebug-&optional-wrapper cursor specs 'edebug-&optional-wrapper))
1678
1679 (defun edebug-&optional-wrapper (cursor specs remainder-handler)
1680   (let (result
1681         (edebug-&optional specs)
1682         (edebug-gate nil)
1683         (this-form (edebug-cursor-expressions cursor))
1684         (this-offset (edebug-cursor-offsets cursor)))
1685     (if (null (catch 'no-match
1686                 (setq result
1687                       (edebug-match-specs cursor specs remainder-handler))
1688                 ;; Returning nil means no no-match was thrown.
1689                 nil))
1690         result
1691       ;; no-match, but don't fail; just reset cursor and return nil.
1692       (edebug-set-cursor cursor this-form this-offset)
1693       nil)))
1694
1695
1696 (defun edebug-&rest-wrapper (cursor specs remainder-handler)
1697   (if (null specs) (setq specs edebug-&rest))
1698   ;; Reuse the &optional handler with this as the remainder handler.
1699   (edebug-&optional-wrapper cursor specs remainder-handler))
1700
1701 (defun edebug-match-&rest (cursor specs)
1702   ;; Repeatedly use specs until failure.
1703   (let ((edebug-&rest specs) ;; remember these
1704         edebug-best-error
1705         edebug-error-point)
1706     (edebug-&rest-wrapper cursor specs 'edebug-&rest-wrapper)))
1707
1708
1709 (defun edebug-match-&or (cursor specs)
1710   ;; Keep matching until one spec succeeds, and return its results.
1711   ;; If none match, fail.
1712   ;; This needs to be optimized since most specs spend time here.
1713   (let ((original-specs specs)
1714         (this-form (edebug-cursor-expressions cursor))
1715         (this-offset (edebug-cursor-offsets cursor)))
1716     (catch 'matched
1717       (while specs
1718         (catch 'no-match
1719           (throw 'matched
1720                  (let (edebug-gate ;; only while matching each spec
1721                        edebug-best-error
1722                        edebug-error-point)
1723                    ;; Doesn't support e.g. &or symbolp &rest form
1724                    (edebug-match-one-spec cursor (car specs)))))
1725         ;; Match failed, so reset and try again.
1726         (setq specs (cdr specs))
1727         ;; Reset the cursor for the next match.
1728         (edebug-set-cursor cursor this-form this-offset))
1729       ;; All failed.
1730       (apply 'edebug-no-match cursor "Expected one of" original-specs))
1731     ))
1732
1733
1734 (defun edebug-match-&not (cursor specs)
1735   ;; If any specs match, then fail
1736   (if (null (catch 'no-match
1737               (let ((edebug-gate nil))
1738                 (save-excursion
1739                   (edebug-match-&or cursor specs)))
1740               nil))
1741       ;; This means something matched, so it is a no match.
1742       (edebug-no-match cursor "Unexpected"))
1743   ;; This means nothing matched, so it is OK.
1744   nil) ;; So, return nothing
1745
1746
1747 (def-edebug-spec &key edebug-match-&key)
1748
1749 (defun edebug-match-&key (cursor specs)
1750   ;; Following specs must look like (<name> <spec>) ...
1751   ;; where <name> is the name of a keyword, and spec is its spec.
1752   ;; This really doesn't save much over the expanded form and takes time.
1753   (edebug-match-&rest
1754    cursor
1755    (cons '&or
1756          (mapcar (function (lambda (pair)
1757                              (vector (format ":%s" (car pair))
1758                                      (car (cdr pair)))))
1759                  specs))))
1760
1761
1762 (defun edebug-match-gate (cursor)
1763   ;; Simply set the gate to prevent backtracking at this level.
1764   (setq edebug-gate t)
1765   nil)
1766
1767
1768 (defun edebug-match-list (cursor specs)
1769   ;; The spec is a list, but what kind of list, and what context?
1770   (if edebug-dotted-spec
1771       ;; After dotted spec but form did not contain dot,
1772       ;; so match list spec elements as if spliced in.
1773       (prog1
1774           (let ((edebug-dotted-spec))
1775             (edebug-match-specs cursor specs 'edebug-match-specs))
1776         ;; If it matched, really clear the dotted-spec flag.
1777         (setq edebug-dotted-spec nil))
1778     (let ((spec (car specs))
1779           (form (edebug-top-element-required cursor "Expected" specs)))
1780       (cond
1781        ((eq 'quote spec)
1782         (let ((spec (car (cdr specs))))
1783           (cond
1784            ((symbolp spec)
1785             ;; Special case: spec quotes a symbol to match.
1786             ;; Change in future.  Use "..." instead.
1787             (if (not (eq spec form))
1788                 (edebug-no-match cursor "Expected" spec))
1789             (edebug-move-cursor cursor)
1790             (setq edebug-gate t)
1791             form)
1792            (t
1793             (error "Bad spec: %s" specs)))))
1794
1795        ((listp form)
1796         (prog1
1797             (list (edebug-match-sublist
1798                    ;; First offset is for the list form itself.
1799                    ;; Treat nil as empty list.
1800                    (edebug-new-cursor form (cdr (edebug-top-offset cursor)))
1801                    specs))
1802           (edebug-move-cursor cursor)))
1803
1804        ((and (eq 'vector spec) (vectorp form))
1805         ;; Special case: match a vector with the specs.
1806         (let ((result (edebug-match-sublist
1807                        (edebug-new-cursor
1808                         form (cdr (edebug-top-offset cursor)))
1809                        (cdr specs))))
1810           (edebug-move-cursor cursor)
1811           (list (apply 'vector result))))
1812
1813        (t (edebug-no-match cursor "Expected" specs)))
1814       )))
1815
1816
1817 (defun edebug-match-sublist (cursor specs)
1818   ;; Match a sublist of specs.
1819   (let (edebug-&optional
1820         ;;edebug-best-error
1821         ;;edebug-error-point
1822         )
1823     (prog1
1824         ;; match with edebug-match-specs so edebug-best-error is not bound.
1825         (edebug-match-specs cursor specs 'edebug-match-specs)
1826       (if (not (edebug-empty-cursor cursor))
1827           (if edebug-best-error
1828               (apply 'edebug-no-match cursor edebug-best-error)
1829             ;; A failed &rest or &optional spec may leave some args.
1830             (edebug-no-match cursor "Failed matching" specs)
1831             )))))
1832
1833
1834 (defun edebug-match-string (cursor spec)
1835   (let ((sexp (edebug-top-element-required cursor "Expected" spec)))
1836     (if (not (eq (intern spec) sexp))
1837         (edebug-no-match cursor "Expected" spec)
1838       ;; Since it matched, failure means immediate error, unless &optional.
1839       (setq edebug-gate t)
1840       (edebug-move-cursor cursor)
1841       (list sexp)
1842       )))
1843
1844 (defun edebug-match-nil (cursor)
1845   ;; There must be nothing left to match a nil.
1846   (if (not (edebug-empty-cursor cursor))
1847       (edebug-no-match cursor "Unmatched argument(s)")
1848     nil))
1849
1850
1851 (defun edebug-match-function (cursor)
1852   (error "Use function-form instead of function in edebug spec"))
1853
1854 (defun edebug-match-&define (cursor specs)
1855   ;; Match a defining form.
1856   ;; Normally, &define is interpreted specially other places.
1857   ;; This should only be called inside of a spec list to match the remainder
1858   ;; of the current list.  e.g. ("lambda" &define args def-body)
1859    (edebug-make-form-wrapper
1860     cursor
1861     (edebug-before-offset cursor)
1862     ;; Find the last offset in the list.
1863     (let ((offsets (edebug-cursor-offsets cursor)))
1864       (while (consp offsets) (setq offsets (cdr offsets)))
1865       offsets)
1866     specs))
1867
1868 (defun edebug-match-lambda-expr (cursor)
1869   ;; The expression must be a function.
1870   ;; This will match any list form that begins with a symbol
1871   ;; that has an edebug-form-spec beginning with &define.  In
1872   ;; practice, only lambda expressions should be used.
1873   ;; I could add a &lambda specification to avoid confusion.
1874   (let* ((sexp (edebug-top-element-required
1875                 cursor "Expected lambda expression"))
1876          (offset (edebug-top-offset cursor))
1877          (head (and (consp sexp) (car sexp)))
1878          (spec (and (symbolp head) (get-edebug-spec head)))
1879          (edebug-inside-func nil))
1880     ;; Find out if this is a defining form from first symbol.
1881     (if (and (consp spec) (eq '&define (car spec)))
1882         (prog1
1883             (list
1884              (edebug-defining-form
1885               (edebug-new-cursor sexp offset)
1886               (car offset);; before the sexp
1887               (edebug-after-offset cursor)
1888               (cons (symbol-name head) (cdr spec))))
1889           (edebug-move-cursor cursor))
1890       (edebug-no-match cursor "Expected lambda expression")
1891       )))
1892
1893
1894 (defun edebug-match-name (cursor)
1895   ;; Set the edebug-def-name bound in edebug-defining-form.
1896   (let ((name (edebug-top-element-required cursor "Expected name")))
1897     ;; Maybe strings and numbers could be used.
1898     (if (not (symbolp name))
1899         (edebug-no-match cursor "Symbol expected for name of definition"))
1900     (setq edebug-def-name
1901           (if edebug-def-name
1902               ;; Construct a new name by appending to previous name.
1903               (intern (format "%s@%s" edebug-def-name name))
1904             name))
1905     (edebug-move-cursor cursor)
1906     (list name)))
1907
1908 (defun edebug-match-colon-name (cursor spec)
1909   ;; Set the edebug-def-name to the spec.
1910   (setq edebug-def-name
1911         (if edebug-def-name
1912             ;; Construct a new name by appending to previous name.
1913             (intern (format "%s@%s" edebug-def-name spec))
1914           spec))
1915   nil)
1916
1917 (defun edebug-match-arg (cursor)
1918   ;; set the def-args bound in edebug-defining-form
1919   (let ((edebug-arg (edebug-top-element-required cursor "Expected arg")))
1920     (if (or (not (symbolp edebug-arg))
1921             (edebug-lambda-list-keywordp edebug-arg))
1922       (edebug-no-match cursor "Bad argument:" edebug-arg))
1923     (edebug-move-cursor cursor)
1924     (setq edebug-def-args (cons edebug-arg edebug-def-args))
1925     (list edebug-arg)))
1926
1927 (defun edebug-match-def-form (cursor)
1928   ;; Like form but the form is wrapped in edebug-enter form.
1929   ;; The form is assumed to be executing outside of the function context.
1930   ;; This is a hack for now, since a def-form might execute inside as well.
1931   ;; Not to be used otherwise.
1932   (let ((edebug-inside-func nil))
1933     (list (edebug-make-enter-wrapper (list (edebug-form cursor))))))
1934
1935 (defun edebug-match-def-body (cursor)
1936   ;; Like body but body is wrapped in edebug-enter form.
1937   ;; The body is assumed to be executing inside of the function context.
1938   ;; Not to be used otherwise.
1939   (let ((edebug-inside-func t))
1940     (list (edebug-wrap-def-body (edebug-forms cursor)))))
1941
1942
1943 ;;;; Edebug Form Specs
1944 ;;; ==========================================================
1945 ;;; See cl-specs.el for common lisp specs.
1946
1947 ;;;;* Spec for def-edebug-spec
1948 ;;; Out of date.
1949
1950 (defun edebug-spec-p (object)
1951   "Return non-nil if OBJECT is a symbol with an edebug-form-spec property."
1952   (and (symbolp object)
1953        (get object 'edebug-form-spec)))
1954
1955 (def-edebug-spec def-edebug-spec
1956   ;; Top level is different from lower levels.
1957   (&define :name edebug-spec name
1958            &or "nil" edebug-spec-p "t" "0" (&rest edebug-spec)))
1959
1960 (def-edebug-spec edebug-spec-list
1961   ;; A list must have something in it, or it is nil, a symbolp
1962   ((edebug-spec . [&or nil edebug-spec])))
1963
1964 (def-edebug-spec edebug-spec
1965   (&or
1966    (vector &rest edebug-spec)           ; matches a vector
1967    ("vector" &rest edebug-spec)         ; matches a vector spec
1968    ("quote" symbolp)
1969    edebug-spec-list
1970    stringp
1971    [edebug-lambda-list-keywordp &rest edebug-spec]
1972    [keywordp gate edebug-spec]
1973    edebug-spec-p  ;; Including all the special ones e.g. form.
1974    symbolp;; a predicate
1975    ))
1976
1977
1978 ;;;* Emacs special forms and some functions.
1979
1980 ;; quote expects only one argument, although it allows any number.
1981 (def-edebug-spec quote sexp)
1982
1983 ;; The standard defining forms.
1984 (def-edebug-spec defconst defvar)
1985 (def-edebug-spec defvar (symbolp &optional form stringp))
1986
1987 (def-edebug-spec defun
1988   (&define name lambda-list
1989            [&optional stringp]
1990            [&optional ("interactive" interactive)]
1991            def-body))
1992 (def-edebug-spec defmacro
1993   (&define name lambda-list [&optional ("declare" &rest sexp)] def-body))
1994
1995 ;; XEmacs addition: this can go away once we support defmacro declarations
1996 (def-edebug-spec define-derived-mode
1997   (&define name symbolp sexp [&optional stringp] [&rest keywordp sexp]
1998    def-body))
1999
2000 ;; XEmacs addition: this should move to easy-mmode.el
2001 (def-edebug-spec define-minor-mode
2002   (&define name stringp
2003    [&optional [&not keywordp] sexp
2004     &optional [&not keywordp] sexp
2005     &optional [&not keywordp] sexp]
2006    [&rest [keywordp sexp]]
2007    def-body))
2008
2009 (def-edebug-spec arglist lambda-list)  ;; deprecated - use lambda-list.
2010
2011 (def-edebug-spec lambda-list
2012   (([&rest arg]
2013     [&optional ["&optional" arg &rest arg]]
2014     &optional ["&rest" arg]
2015     )))
2016
2017 (def-edebug-spec interactive
2018   (&optional &or stringp def-form))
2019
2020 ;; A function-form is for an argument that may be a function or a form.
2021 ;; This specially recognizes anonymous functions quoted with quote.
2022 (def-edebug-spec function-form
2023   ;; form at the end could also handle "function",
2024   ;; but recognize it specially to avoid wrapping function forms.
2025   ;; XEmacs addition: also check for function*
2026   (&or ([&or "quote" "function" "function*"] &or symbolp lambda-expr) form))
2027
2028 ;; function expects a symbol or a lambda or macro expression
2029 ;; A macro is allowed by Emacs.
2030 (def-edebug-spec function (&or symbolp lambda-expr))
2031
2032 ;; lambda is a macro in emacs 19.
2033 (def-edebug-spec lambda (&define lambda-list
2034                                  [&optional stringp]
2035                                  [&optional ("interactive" interactive)]
2036                                  def-body))
2037
2038 ;; A macro expression is a lambda expression with "macro" prepended.
2039 (def-edebug-spec macro (&define "lambda" lambda-list def-body))
2040
2041 ;; (def-edebug-spec anonymous-form ((&or ["lambda" lambda] ["macro" macro])))
2042
2043 ;; Standard functions that take function-forms arguments.
2044 (def-edebug-spec mapcar (function-form form))
2045 (def-edebug-spec mapconcat (function-form form form))
2046 (def-edebug-spec mapatoms (function-form &optional form))
2047 (def-edebug-spec apply (function-form &rest form))
2048 (def-edebug-spec funcall (function-form &rest form))
2049
2050 (def-edebug-spec let
2051   ((&rest &or (symbolp &optional form) symbolp)
2052    body))
2053
2054 (def-edebug-spec let* let)
2055
2056 (def-edebug-spec setq (&rest symbolp form))
2057 (def-edebug-spec setq-default setq)
2058
2059 (def-edebug-spec cond (&rest (&rest form)))
2060
2061 (def-edebug-spec condition-case
2062   (symbolp
2063    form
2064    &rest ([&or symbolp (&rest symbolp)] body)))
2065
2066
2067 (def-edebug-spec \` (backquote-form))
2068
2069 ;; Supports quotes inside backquotes,
2070 ;; but only at the top level inside unquotes.
2071 (def-edebug-spec backquote-form
2072   (&or
2073    ([&or "," ",@"] &or ("quote" backquote-form) form)
2074    ;; The simple version:
2075    ;;   (backquote-form &rest backquote-form)
2076    ;; doesn't handle (a . ,b).  The straightforward fix:
2077    ;;   (backquote-form . [&or nil backquote-form])
2078    ;; uses up too much stack space.
2079    ;; Note that `(foo . ,@bar) is not legal, so we don't need to handle it.
2080    (backquote-form [&rest [&not ","] backquote-form]
2081                    . [&or nil backquote-form])
2082    ;; If you use dotted forms in backquotes, replace the previous line
2083    ;; with the following.  This takes quite a bit more stack space, however.
2084    ;; (backquote-form . [&or nil backquote-form])
2085    (vector &rest backquote-form)
2086    sexp))
2087
2088 ;; Special version of backquote that instruments backquoted forms
2089 ;; destined to be evaluated, usually as the result of a
2090 ;; macroexpansion.  Backquoted code can only have unquotes (, and ,@)
2091 ;; in places where list forms are allowed, and predicates. If the
2092 ;; backquote is used in a macro, unquoted code that come from
2093 ;; arguments must be instrumented, if at all, with def-form not def-body.
2094
2095 ;; We could assume that all forms (not nested in other forms)
2096 ;; in arguments of macros should be def-forms, whether or not the macros
2097 ;; are defined with edebug-` but this would be expensive.
2098
2099 ;; ,@ might have some problems.
2100
2101 (defalias 'edebug-\` '\`)  ;; same macro as regular backquote.
2102 (def-edebug-spec edebug-\` (def-form))
2103
2104 ;; Assume immediate quote in unquotes mean backquote at next higher level.
2105 (def-edebug-spec , (&or ("quote" edebug-\`) def-form))
2106 (def-edebug-spec ,@ (&define  ;; so (,@ form) is never wrapped.
2107                      &or ("quote" edebug-\`) def-form))
2108
2109 ;; New byte compiler.
2110 (def-edebug-spec defsubst defun)
2111 (def-edebug-spec dont-compile t)
2112 (def-edebug-spec eval-when-compile t)
2113 (def-edebug-spec eval-and-compile t)
2114
2115 (def-edebug-spec save-selected-window t)
2116 (def-edebug-spec save-current-buffer t)
2117 (def-edebug-spec delay-mode-hooks t)
2118 (def-edebug-spec with-temp-file t)
2119 (def-edebug-spec with-temp-message t)
2120 (def-edebug-spec with-syntax-table t)
2121 (def-edebug-spec push (form sexp))
2122 (def-edebug-spec pop (sexp))
2123
2124 (def-edebug-spec 1value (form))
2125 (def-edebug-spec noreturn (form))
2126
2127 ;; XEmacs additions
2128 (def-edebug-spec save-match-data t)
2129 (def-edebug-spec with-output-to-string t)
2130 (def-edebug-spec with-current-buffer t)
2131 (def-edebug-spec with-temp-buffer t)
2132
2133 ;; Anything else?
2134
2135
2136 ;; Some miscellaneous specs for macros in public packages.
2137 ;; Send me yours.
2138
2139 ;; advice.el by Hans Chalupsky (hans@cs.buffalo.edu)
2140
2141 (def-edebug-spec ad-dolist ((symbolp form &optional form) body))
2142 (def-edebug-spec defadvice
2143   (&define name   ;; thing being advised.
2144            (name  ;; class is [&or "before" "around" "after"
2145                   ;;               "activation" "deactivation"]
2146             name  ;; name of advice
2147             &rest sexp  ;; optional position and flags
2148             )
2149            [&optional stringp]
2150            [&optional ("interactive" interactive)]
2151            def-body))
2152
2153 (def-edebug-spec easy-menu-define (symbolp body))
2154
2155 (def-edebug-spec with-custom-print body)
2156
2157 (def-edebug-spec sregexq (&rest sexp))
2158 (def-edebug-spec rx (&rest sexp))
2159
2160 ;;; The debugger itself
2161
2162 (defvar edebug-active nil)  ;; Non-nil when edebug is active
2163
2164 ;;; add minor-mode-alist entry
2165 (or (assq 'edebug-active minor-mode-alist)
2166     (setq minor-mode-alist (cons (list 'edebug-active " *Debugging*")
2167                                  minor-mode-alist)))
2168
2169 (defvar edebug-stack nil)
2170 ;; Stack of active functions evaluated via edebug.
2171 ;; Should be nil at the top level.
2172
2173 (defvar edebug-stack-depth -1)
2174 ;; Index of last edebug-stack item.
2175
2176 (defvar edebug-offset-indices nil)
2177 ;; Stack of offset indices of visited edebug sexps.
2178 ;; Should be nil at the top level.
2179 ;; Each function adds one cons.  Top is modified with setcar.
2180
2181
2182 (defvar edebug-entered nil
2183   ;; Non-nil if edebug has already been entered at this recursive edit level.
2184   ;; This should stay nil at the top level.
2185   )
2186
2187 ;; Should these be options?
2188 (defconst edebug-debugger 'edebug
2189   ;; Name of function to use for debugging when error or quit occurs.
2190   ;; Set this to 'debug if you want to debug edebug.
2191   )
2192
2193
2194 ;; Dynamically bound variables, declared globally but left unbound.
2195 (defvar edebug-function) ; the function being executed. change name!!
2196 (defvar edebug-args) ; the arguments of the function
2197 (defvar edebug-data) ; the edebug data for the function
2198 (defvar edebug-value) ; the result of the expression
2199 (defvar edebug-after-index)
2200 (defvar edebug-def-mark) ; the mark for the definition
2201 (defvar edebug-freq-count) ; the count of expression visits.
2202 (defvar edebug-coverage) ; the coverage results of each expression of function.
2203
2204 (defvar edebug-buffer) ; which buffer the function is in.
2205 (defvar edebug-result) ; the result of the function call returned by body
2206 (defvar edebug-outside-executing-macro)
2207 (defvar edebug-outside-defining-kbd-macro)
2208
2209 (defvar edebug-execution-mode 'step) ; Current edebug mode set by user.
2210 (defvar edebug-next-execution-mode nil) ; Use once instead of initial mode.
2211
2212 (defvar edebug-outside-debug-on-error) ; the value of debug-on-error outside
2213 (defvar edebug-outside-debug-on-quit) ; the value of debug-on-quit outside
2214
2215 (defvar edebug-outside-overriding-local-map)
2216 (defvar edebug-outside-overriding-terminal-local-map)
2217
2218 (defvar edebug-outside-pre-command-hook)
2219 (defvar edebug-outside-post-command-hook)
2220
2221 (defvar cl-lexical-debug)  ;; Defined in cl.el
2222
2223 ;;; Handling signals
2224
2225 (defun edebug-signal (edebug-signal-name edebug-signal-data)
2226   "Signal an error.  Args are SIGNAL-NAME, and associated DATA.
2227 A signal name is a symbol with an `error-conditions' property
2228 that is a list of condition names.
2229 A handler for any of those names will get to handle this signal.
2230 The symbol `error' should always be one of them.
2231
2232 DATA should be a list.  Its elements are printed as part of the error message.
2233 If the signal is handled, DATA is made available to the handler.
2234 See `condition-case'.
2235
2236 This is the Edebug replacement for the standard `signal'.  It should
2237 only be active while Edebug is.  It checks `debug-on-error' to see
2238 whether it should call the debugger.  When execution is resumed, the
2239 error is signaled again."
2240   (if (and (listp debug-on-error) (memq edebug-signal-name debug-on-error))
2241       (edebug 'error (cons edebug-signal-name edebug-signal-data)))
2242   ;; If we reach here without another non-local exit, then send signal again.
2243   ;; i.e. the signal is not continuable, yet.
2244   ;; Avoid infinite recursion.
2245   (let ((signal-hook-function nil))
2246     (signal edebug-signal-name edebug-signal-data)))
2247
2248 ;;; Entering Edebug
2249
2250 (defun edebug-enter (edebug-function edebug-args edebug-body)
2251   ;; Entering FUNC.  The arguments are ARGS, and the body is BODY.
2252   ;; Setup edebug variables and evaluate BODY.  This function is called
2253   ;; when a function evaluated with edebug-eval-top-level-form is entered.
2254   ;; Return the result of BODY.
2255
2256   ;; Is this the first time we are entering edebug since
2257   ;; lower-level recursive-edit command?
2258   ;; More precisely, this tests whether Edebug is currently active.
2259   (if (not edebug-entered)
2260       (let ((edebug-entered t)
2261             ;; Binding max-lisp-eval-depth here is OK,
2262             ;; but not inside an unwind-protect.
2263             ;; Doing it here also keeps it from growing too large.
2264             (max-lisp-eval-depth (+ 100 max-lisp-eval-depth)) ; too much??
2265             (max-specpdl-size (+ 200 max-specpdl-size))
2266
2267             (debugger edebug-debugger)  ; only while edebug is active.
2268             (edebug-outside-debug-on-error debug-on-error)
2269             (edebug-outside-debug-on-quit debug-on-quit)
2270             ;; Binding these may not be the right thing to do.
2271             ;; We want to allow the global values to be changed.
2272             (debug-on-error (or debug-on-error edebug-on-error))
2273             (debug-on-quit edebug-on-quit)
2274
2275             ;; Lexical bindings must be uncompiled for this to work.
2276             (cl-lexical-debug t)
2277
2278             (edebug-outside-overriding-local-map overriding-local-map)
2279             (edebug-outside-overriding-terminal-local-map
2280              overriding-terminal-local-map)
2281
2282             ;; Save the outside value of executing macro.  (here??)
2283             (edebug-outside-executing-macro executing-kbd-macro)
2284             (edebug-outside-pre-command-hook
2285              (edebug-var-status 'pre-command-hook))
2286             (edebug-outside-post-command-hook
2287              (edebug-var-status 'post-command-hook)))
2288         (unwind-protect
2289             (let (;; Don't keep reading from an executing kbd macro
2290                   ;; within edebug unless edebug-continue-kbd-macro is
2291                   ;; non-nil.  Again, local binding may not be best.
2292                   (executing-kbd-macro
2293                    (if edebug-continue-kbd-macro executing-kbd-macro))
2294
2295                   ;; Don't get confused by the user's keymap changes.
2296                   (overriding-local-map nil)
2297                   (overriding-terminal-local-map nil)
2298
2299                   (signal-hook-function 'edebug-signal)
2300
2301                   ;; Disable command hooks.  This is essential when
2302                   ;; a hook function is instrumented - to avoid infinite loop.
2303                   ;; This may be more than we need, however.
2304                   (pre-command-hook nil)
2305                   (post-command-hook nil))
2306               (setq edebug-execution-mode (or edebug-next-execution-mode
2307                                               edebug-initial-mode
2308                                               edebug-execution-mode)
2309                     edebug-next-execution-mode nil)
2310               (edebug-enter edebug-function edebug-args edebug-body))
2311           ;; Reset global variables in case outside value was changed.
2312           (setq executing-kbd-macro edebug-outside-executing-macro)
2313           (edebug-restore-status
2314            'post-command-hook edebug-outside-post-command-hook)
2315           (edebug-restore-status
2316            'pre-command-hook edebug-outside-pre-command-hook)))
2317
2318     (let* ((edebug-data (get edebug-function 'edebug))
2319            (edebug-def-mark (car edebug-data)) ; mark at def start
2320            (edebug-freq-count (get edebug-function 'edebug-freq-count))
2321            (edebug-coverage (get edebug-function 'edebug-coverage))
2322            (edebug-buffer (marker-buffer edebug-def-mark))
2323
2324            (edebug-stack (cons edebug-function edebug-stack))
2325            (edebug-offset-indices (cons 0 edebug-offset-indices))
2326            )
2327       (if (get edebug-function 'edebug-on-entry)
2328           (progn
2329             (setq edebug-execution-mode 'step)
2330             (if (eq (get edebug-function 'edebug-on-entry) 'temp)
2331                 (put edebug-function 'edebug-on-entry nil))))
2332       (if edebug-trace
2333           (edebug-enter-trace edebug-body)
2334         (funcall edebug-body))
2335       )))
2336
2337 (defun edebug-var-status (var)
2338   "Return a cons cell describing the status of VAR's current binding.
2339 The purpose of this function is so you can properly undo
2340 subsequent changes to the same binding, by passing the status
2341 cons cell to `edebug-restore-status'.  The status cons cell
2342 has the form (LOCUS . VALUE), where LOCUS can be a buffer
2343 \(for a buffer-local binding), a frame (for a frame-local binding),
2344 or nil (if the default binding is current)."
2345   (cons (and (fboundp 'variable-binding-locus) (variable-binding-locus var))
2346         (symbol-value var)))
2347
2348 (defun edebug-restore-status (var status)
2349   "Reset VAR based on STATUS.
2350 STATUS should be a list you got from `edebug-var-status'."
2351   (let ((locus (car status))
2352         (value (cdr status)))
2353     (cond ((bufferp locus)
2354            (if (buffer-live-p locus)
2355                (with-current-buffer locus
2356                  (set var value))))
2357           ((framep locus)
2358            (modify-frame-parameters locus (list (cons var value))))
2359           (t
2360            (set var value)))))
2361
2362 (defun edebug-enter-trace (edebug-body)
2363   (let ((edebug-stack-depth (1+ edebug-stack-depth))
2364         edebug-result)
2365     (edebug-print-trace-before
2366      (format "%s args: %s" edebug-function edebug-args))
2367     (prog1 (setq edebug-result (funcall edebug-body))
2368       (edebug-print-trace-after
2369        (format "%s result: %s" edebug-function edebug-result)))))
2370
2371 (def-edebug-spec edebug-tracing (form body))
2372
2373 (defmacro edebug-tracing (msg &rest body)
2374   "Print MSG in *edebug-trace* before and after evaluating BODY.
2375 The result of BODY is also printed."
2376   `(let ((edebug-stack-depth (1+ edebug-stack-depth))
2377          edebug-result)
2378      (edebug-print-trace-before ,msg)
2379      (prog1 (setq edebug-result (progn ,@body))
2380        (edebug-print-trace-after
2381         (format "%s result: %s" ,msg edebug-result)))))
2382
2383 (defun edebug-print-trace-before (msg)
2384   "Function called to print trace info before expression evaluation.
2385 MSG is printed after `::::{ '."
2386   (edebug-trace-display
2387    edebug-trace-buffer "%s{ %s" (make-string edebug-stack-depth ?\:) msg))
2388
2389 (defun edebug-print-trace-after (msg)
2390   "Function called to print trace info after expression evaluation.
2391 MSG is printed after `::::} '."
2392   (edebug-trace-display
2393    edebug-trace-buffer "%s} %s" (make-string edebug-stack-depth ?\:) msg))
2394
2395
2396
2397 (defun edebug-slow-before (edebug-before-index)
2398   ;; Debug current function given BEFORE position.
2399   ;; Called from functions compiled with edebug-eval-top-level-form.
2400   ;; Return the before index.
2401   (setcar edebug-offset-indices edebug-before-index)
2402
2403   ;; Increment frequency count
2404   (aset edebug-freq-count edebug-before-index
2405         (1+ (aref edebug-freq-count edebug-before-index)))
2406
2407   (if (or (not (memq edebug-execution-mode '(Go-nonstop next)))
2408           (edebug-input-pending-p))
2409       (edebug-debugger edebug-before-index 'before nil))
2410   edebug-before-index)
2411
2412 (defun edebug-fast-before (edebug-before-index)
2413   ;; Do nothing.
2414   )
2415
2416 (defun edebug-slow-after (edebug-before-index edebug-after-index edebug-value)
2417   ;; Debug current function given AFTER position and VALUE.
2418   ;; Called from functions compiled with edebug-eval-top-level-form.
2419   ;; Return VALUE.
2420   (setcar edebug-offset-indices edebug-after-index)
2421
2422   ;; Increment frequency count
2423   (aset edebug-freq-count edebug-after-index
2424         (1+ (aref edebug-freq-count edebug-after-index)))
2425   (if edebug-test-coverage (edebug-update-coverage))
2426
2427   (if (and (eq edebug-execution-mode 'Go-nonstop)
2428            (not (edebug-input-pending-p)))
2429       ;; Just return result.
2430       edebug-value
2431     (edebug-debugger edebug-after-index 'after edebug-value)
2432     ))
2433
2434 (defun edebug-fast-after (edebug-before-index edebug-after-index edebug-value)
2435   ;; Do nothing but return the value.
2436   edebug-value)
2437
2438 (defun edebug-run-slow ()
2439   (defalias 'edebug-before 'edebug-slow-before)
2440   (defalias 'edebug-after 'edebug-slow-after))
2441
2442 ;; This is not used, yet.
2443 (defun edebug-run-fast ()
2444   (defalias 'edebug-before 'edebug-fast-before)
2445   (defalias 'edebug-after 'edebug-fast-after))
2446
2447 (edebug-run-slow)
2448
2449
2450 (defun edebug-update-coverage ()
2451   (let ((old-result (aref edebug-coverage edebug-after-index)))
2452     (cond
2453      ((eq 'ok-coverage old-result))
2454      ((eq 'unknown old-result)
2455       (aset edebug-coverage edebug-after-index edebug-value))
2456      ;; Test if a different result.
2457      ((not (eq edebug-value old-result))
2458       (aset edebug-coverage edebug-after-index 'ok-coverage)))))
2459
2460
2461 ;; Dynamically declared unbound variables.
2462 (defvar edebug-arg-mode)  ; the mode, either before, after, or error
2463 (defvar edebug-breakpoints)
2464 (defvar edebug-break-data) ; break data for current function.
2465 (defvar edebug-break) ; whether a break occurred.
2466 (defvar edebug-global-break) ; whether a global break occurred.
2467 (defvar edebug-break-condition) ; whether the breakpoint is conditional.
2468
2469 (defvar edebug-break-result nil)
2470 (defvar edebug-global-break-result nil)
2471
2472
2473 (defun edebug-debugger (edebug-offset-index edebug-arg-mode edebug-value)
2474   (if nil ;;FSF 21.3 inhibit-redisplay
2475       ;; Don't really try to enter edebug within an eval from redisplay.
2476       edebug-value
2477     ;; Check breakpoints and pending input.
2478     ;; If edebug display should be updated, call edebug-display.
2479     ;; Return edebug-value.
2480     (let* ( ;; This needs to be here since breakpoints may be changed.
2481            (edebug-breakpoints (car (cdr edebug-data))) ; list of breakpoints
2482            (edebug-break-data (assq edebug-offset-index edebug-breakpoints))
2483            (edebug-break-condition (car (cdr edebug-break-data)))
2484            (edebug-global-break
2485             (if edebug-global-break-condition
2486                 (condition-case nil
2487                     (setq edebug-global-break-result
2488                           (eval edebug-global-break-condition))
2489                   (error nil))))
2490            (edebug-break))
2491
2492 ;;;    (edebug-trace "exp: %s" edebug-value)
2493       ;; Test whether we should break.
2494       (setq edebug-break
2495             (or edebug-global-break
2496                 (and edebug-break-data
2497                      (or (not edebug-break-condition)
2498                          (setq edebug-break-result
2499                                (eval edebug-break-condition))))))
2500       (if (and edebug-break
2501                (nth 2 edebug-break-data)) ; is it temporary?
2502           ;; Delete the breakpoint.
2503           (setcdr edebug-data
2504                   (cons (delq edebug-break-data edebug-breakpoints)
2505                         (cdr (cdr edebug-data)))))
2506
2507       ;; Display if mode is not go, continue, or Continue-fast
2508       ;; or break, or input is pending,
2509       (if (or (not (memq edebug-execution-mode '(go continue Continue-fast)))
2510               edebug-break
2511               (edebug-input-pending-p))
2512           (edebug-display))             ; <--------------- display
2513
2514       edebug-value
2515       )))
2516
2517
2518 ;; window-start now stored with each function.
2519 ;;(defvar edebug-window-start nil)
2520 ;; Remember where each buffers' window starts between edebug calls.
2521 ;; This is to avoid spurious recentering.
2522 ;; Does this still need to be buffer-local??
2523 ;;(setq-default edebug-window-start nil)
2524 ;;(make-variable-buffer-local 'edebug-window-start)
2525
2526
2527 ;; Dynamically declared unbound vars
2528 (defvar edebug-point) ; the point in edebug buffer
2529 (defvar edebug-outside-buffer) ; the current-buffer outside of edebug
2530 (defvar edebug-outside-point) ; the point outside of edebug
2531 (defvar edebug-outside-mark) ; the mark outside of edebug
2532 (defvar edebug-window-data)  ; window and window-start for current function
2533 (defvar edebug-outside-windows) ; outside window configuration
2534 (defvar edebug-eval-buffer) ; for the evaluation list.
2535 (defvar edebug-outside-o-a-p) ; outside overlay-arrow-position
2536 (defvar edebug-outside-o-a-s) ; outside overlay-arrow-string
2537 (defvar edebug-outside-c-i-e-a) ; outside cursor-in-echo-area
2538
2539 (defvar edebug-eval-list nil) ;; List of expressions to evaluate.
2540
2541 (defvar edebug-previous-result nil) ;; Last result returned.
2542
2543 ;; Emacs 19 adds an arg to mark and mark-marker.
2544 ;; XEmacs change: do not just alias mark-marker
2545 (defun edebug-mark-marker ()
2546   (let ((zmacs-regions nil))
2547     (mark-marker)))
2548
2549
2550 (defun edebug-display ()
2551   (unless (marker-position edebug-def-mark)
2552     ;; The buffer holding the source has been killed.
2553     ;; Let's at least show a backtrace so the user can figure out
2554     ;; which function we're talking about.
2555     (debug))
2556   ;; Setup windows for edebug, determine mode, maybe enter recursive-edit.
2557   ;; Uses local variables of edebug-enter, edebug-before, edebug-after
2558   ;; and edebug-debugger.
2559   (let ((edebug-active t)               ; for minor mode alist
2560         edebug-stop                     ; should we enter recursive-edit
2561         (edebug-point (+ edebug-def-mark
2562                          (aref (nth 2 edebug-data) edebug-offset-index)))
2563         edebug-buffer-outside-point     ; current point in edebug-buffer
2564         ;; window displaying edebug-buffer
2565         (edebug-window-data (nth 3 edebug-data))
2566         (edebug-outside-window (selected-window))
2567         (edebug-outside-buffer (current-buffer))
2568         (edebug-outside-point (point))
2569         (edebug-outside-mark (edebug-mark))
2570         edebug-outside-windows          ; window or screen configuration
2571         edebug-buffer-points
2572
2573         edebug-eval-buffer              ; declared here so we can kill it below
2574         (edebug-eval-result-list (and edebug-eval-list
2575                                       (edebug-eval-result-list)))
2576         edebug-trace-window
2577         edebug-trace-window-start
2578
2579         (edebug-outside-o-a-p overlay-arrow-position)
2580         (edebug-outside-o-a-s overlay-arrow-string)
2581         (edebug-outside-c-i-e-a cursor-in-echo-area))
2582     (unwind-protect
2583         (let ((overlay-arrow-position overlay-arrow-position)
2584               (overlay-arrow-string overlay-arrow-string)
2585               (cursor-in-echo-area nil)
2586               ;; any others??
2587               )
2588           (if (not (buffer-name edebug-buffer))
2589               (let ((debug-on-error nil))
2590                 (error "Buffer defining %s not found" edebug-function)))
2591
2592           (if (eq 'after edebug-arg-mode)
2593               ;; Compute result string now before windows are modified.
2594               (edebug-compute-previous-result edebug-value))
2595
2596           (if edebug-save-windows
2597               ;; Save windows now before we modify them.
2598               (setq edebug-outside-windows
2599                     (edebug-current-windows edebug-save-windows)))
2600
2601           (if edebug-save-displayed-buffer-points
2602               (setq edebug-buffer-points (edebug-get-displayed-buffer-points)))
2603
2604           ;; First move the edebug buffer point to edebug-point
2605           ;; so that window start doesn't get changed when we display it.
2606           ;; I don't know if this is going to help.
2607           ;;(set-buffer edebug-buffer)
2608           ;;(goto-char edebug-point)
2609
2610           ;; If edebug-buffer is not currently displayed,
2611           ;; first find a window for it.
2612           (edebug-pop-to-buffer edebug-buffer (car edebug-window-data))
2613           (setcar edebug-window-data (selected-window))
2614
2615           ;; Now display eval list, if any.
2616           ;; This is done after the pop to edebug-buffer
2617           ;; so that buffer-window correspondence is correct after quitting.
2618           (edebug-eval-display edebug-eval-result-list)
2619           ;; The evaluation list better not have deleted edebug-window-data.
2620           (select-window (car edebug-window-data))
2621           (set-buffer edebug-buffer)
2622
2623           (setq edebug-buffer-outside-point (point))
2624           (goto-char edebug-point)
2625
2626           (if (eq 'before edebug-arg-mode)
2627               ;; Check whether positions are up-to-date.
2628               ;; This assumes point is never before symbol.
2629               (if (not (memq (char-after) '(?\( ?\# ?\` )))
2630                   (let ((debug-on-error nil))
2631                     (error "Source has changed - reevaluate definition of %s"
2632                            edebug-function)
2633                     )))
2634
2635           (setcdr edebug-window-data
2636                   (edebug-adjust-window (cdr edebug-window-data)))
2637
2638           ;; Test if there is input, not including keyboard macros.
2639           (if (edebug-input-pending-p)
2640               (progn
2641                 (setq edebug-execution-mode 'step
2642                       edebug-stop t)
2643                 (edebug-stop)
2644                 ;;          (discard-input)             ; is this unfriendly??
2645                 ))
2646           ;; Now display arrow based on mode.
2647           (edebug-overlay-arrow)
2648
2649           (cond
2650            ((eq 'error edebug-arg-mode)
2651             ;; Display error message
2652             (setq edebug-execution-mode 'step)
2653             (edebug-overlay-arrow)
2654             (beep)
2655             (if (eq 'quit (car edebug-value))
2656                 (message "Quit")
2657               (edebug-report-error edebug-value)))
2658            (edebug-break
2659             (cond
2660              (edebug-global-break
2661               (message "Global Break: %s => %s"
2662                        edebug-global-break-condition
2663                        edebug-global-break-result))
2664              (edebug-break-condition
2665               (message "Break: %s => %s"
2666                        edebug-break-condition
2667                        edebug-break-result))
2668              ((not (eq edebug-execution-mode 'Continue-fast))
2669               (message "Break"))
2670              (t)))
2671
2672            (t (message "")))
2673
2674           (if (eq 'after edebug-arg-mode)
2675               (progn
2676                 ;; Display result of previous evaluation.
2677                 (if (and edebug-break
2678                          (not (eq edebug-execution-mode 'Continue-fast)))
2679                     (sit-for 1))        ; Show break message.
2680                 (edebug-previous-result)))
2681
2682           (cond
2683            (edebug-break
2684             (cond
2685              ((eq edebug-execution-mode 'continue) (edebug-sit-for 1))
2686              ((eq edebug-execution-mode 'Continue-fast) (edebug-sit-for 0))
2687              (t (setq edebug-stop t))))
2688            ;; not edebug-break
2689            ((eq edebug-execution-mode 'trace)
2690             (edebug-sit-for edebug-sit-for-seconds)) ; Force update and pause.
2691            ((eq edebug-execution-mode 'Trace-fast)
2692             (edebug-sit-for 0))         ; Force update and continue.
2693            )
2694
2695           (unwind-protect
2696               (if (or edebug-stop
2697                       (memq edebug-execution-mode '(step next))
2698                       (eq edebug-arg-mode 'error))
2699                   (progn
2700                     ;; (setq edebug-execution-mode 'step)
2701                     ;; (edebug-overlay-arrow)   ; This doesn't always show up.
2702                     (edebug-recursive-edit))) ; <---------- Recursive edit
2703
2704             ;; Reset the edebug-window-data to whatever it is now.
2705             (let ((window (if (eq (window-buffer) edebug-buffer)
2706                               (selected-window)
2707                             (edebug-get-buffer-window edebug-buffer))))
2708               ;; Remember window-start for edebug-buffer, if still displayed.
2709               (if window
2710                   (progn
2711                     (setcar edebug-window-data window)
2712                     (setcdr edebug-window-data (window-start window)))))
2713
2714             ;; Save trace window point before restoring outside windows.
2715             ;; Could generalize this for other buffers.
2716             (setq edebug-trace-window (get-buffer-window edebug-trace-buffer))
2717             (if edebug-trace-window
2718                 (setq edebug-trace-window-start
2719                       (and edebug-trace-window
2720                            (window-start edebug-trace-window))))
2721
2722             ;; Restore windows before continuing.
2723             (if edebug-save-windows
2724                 (progn
2725                   (edebug-set-windows edebug-outside-windows)
2726
2727                   ;; Restore displayed buffer points.
2728                   ;; Needed even if restoring windows because
2729                   ;; window-points are not restored. (should they be??)
2730                   (if edebug-save-displayed-buffer-points
2731                       (edebug-set-buffer-points edebug-buffer-points))
2732
2733                   ;; Unrestore trace window's window-point.
2734                   (if edebug-trace-window
2735                       (set-window-start edebug-trace-window
2736                                         edebug-trace-window-start))
2737
2738                   ;; Unrestore edebug-buffer's window-start, if displayed.
2739                   (let ((window (car edebug-window-data)))
2740                     (if (and window (edebug-window-live-p window)
2741                              (eq (window-buffer) edebug-buffer))
2742                         (progn
2743                           (set-window-start window (cdr edebug-window-data)
2744                                             'no-force)
2745                           ;; Unrestore edebug-buffer's window-point.
2746                           ;; Needed in addition to setting the buffer point
2747                           ;; - otherwise quitting doesn't leave point as is.
2748                           ;; But this causes point to not be restored at times.
2749                           ;; Also, it may not be a visible window.
2750                           ;; (set-window-point window edebug-point)
2751                           )))
2752
2753                   ;; Unrestore edebug-buffer's point.   Rerestored below.
2754                   ;;  (goto-char edebug-point) ;; in edebug-buffer
2755                   )
2756               ;; Since we may be in a save-excursion, in case of quit,
2757               ;; reselect the outside window only.
2758               ;; Only needed if we are not recovering windows??
2759               (if (edebug-window-live-p edebug-outside-window)
2760                   (select-window edebug-outside-window))
2761               )                         ; if edebug-save-windows
2762
2763             ;; Restore current buffer always, in case application needs it.
2764             (set-buffer edebug-outside-buffer)
2765             ;; Restore point, and mark.
2766             ;; Needed even if restoring windows because
2767             ;; that doesn't restore point and mark in the current buffer.
2768             ;; But don't restore point if edebug-buffer is current buffer.
2769             (if (not (eq edebug-buffer edebug-outside-buffer))
2770                 (goto-char edebug-outside-point))
2771             (if (marker-buffer (edebug-mark-marker))
2772                 ;; Does zmacs-regions need to be nil while doing set-marker?
2773                 (set-marker (edebug-mark-marker) edebug-outside-mark))
2774             )                           ; unwind-protect
2775           ;; None of the following is done if quit or signal occurs.
2776
2777           ;; Restore edebug-buffer's outside point.
2778           ;;    (edebug-trace "restore edebug-buffer point: %s"
2779           ;;              edebug-buffer-outside-point)
2780           (let ((current-buffer (current-buffer)))
2781             (set-buffer edebug-buffer)
2782             (goto-char edebug-buffer-outside-point)
2783             (set-buffer current-buffer))
2784           ;; ... nothing more.
2785           )
2786       ;; Reset global variables to outside values in case they were changed.
2787       (setq
2788        overlay-arrow-position edebug-outside-o-a-p
2789        overlay-arrow-string edebug-outside-o-a-s
2790        cursor-in-echo-area edebug-outside-c-i-e-a)
2791       )))
2792
2793
2794 (defvar edebug-number-of-recursions 0)
2795 ;; Number of recursive edits started by edebug.
2796 ;; Should be 0 at the top level.
2797
2798 (defvar edebug-recursion-depth 0)
2799 ;; Value of recursion-depth when edebug was called.
2800
2801 ;; Dynamically declared unbound vars
2802 (defvar edebug-outside-match-data) ; match data outside of edebug
2803 (defvar edebug-backtrace-buffer) ; each recursive edit gets its own
2804 (defvar edebug-inside-windows)
2805 (defvar edebug-interactive-p)
2806
2807 (defvar edebug-outside-map)
2808 (defvar edebug-outside-standard-output)
2809 (defvar edebug-outside-standard-input)
2810 (defvar edebug-outside-current-prefix-arg)
2811 (defvar edebug-outside-last-command-char)
2812 (defvar edebug-outside-last-command)
2813 (defvar edebug-outside-this-command)
2814 (defvar edebug-outside-last-input-char)
2815
2816 ;; Note: here we have defvars for variables that are
2817 ;; built-in in certain versions.
2818 ;; Each defvar makes a difference
2819 ;; in versions where the variable is *not* built-in.
2820
2821 ;; Emacs 18
2822 (defvar edebug-outside-unread-command-char)
2823
2824 ;; XEmacs
2825 (defvar edebug-outside-unread-command-event)  ;; like unread-command-events
2826 (defvar unread-command-event nil)
2827
2828 ;; Emacs 19.
2829 (defvar edebug-outside-last-command-event)
2830 (defvar edebug-outside-unread-command-events)
2831 (defvar edebug-outside-last-input-event)
2832 (defvar edebug-outside-last-event-frame)
2833 (defvar edebug-outside-last-nonmenu-event)
2834 (defvar edebug-outside-track-mouse)
2835
2836 ;; Disable byte compiler warnings about unread-command-char and -event
2837 ;; (maybe works with byte-compile-version 2.22 at least)
2838 (defvar edebug-unread-command-char-warning)
2839 (defvar edebug-unread-command-event-warning)
2840 (eval-when-compile
2841   (setq edebug-unread-command-char-warning
2842         (get 'unread-command-char 'byte-obsolete-variable))
2843   (put 'unread-command-char 'byte-obsolete-variable nil)
2844   ;; XEmacs addition
2845   (setq edebug-unread-command-event-warning
2846         (get 'unread-command-event 'byte-obsolete-variable))
2847   (put 'unread-command-event 'byte-obsolete-variable nil))
2848
2849 (defun edebug-recursive-edit ()
2850   ;; Start up a recursive edit inside of edebug.
2851   ;; The current buffer is the edebug-buffer, which is put into edebug-mode.
2852   ;; Assume that none of the variables below are buffer-local.
2853   (let ((edebug-buffer-read-only buffer-read-only)
2854         ;; match-data must be done in the outside buffer
2855         (edebug-outside-match-data
2856          (save-excursion  ; might be unnecessary now??
2857            (set-buffer edebug-outside-buffer)  ; in case match buffer different
2858            (match-data)))
2859
2860         ;;(edebug-number-of-recursions (1+ edebug-number-of-recursions))
2861         (edebug-recursion-depth (recursion-depth))
2862         edebug-entered                  ; bind locally to nil
2863         (edebug-interactive-p nil)      ; again non-interactive
2864         edebug-backtrace-buffer         ; each recursive edit gets its own
2865         ;; The window configuration may be saved and restored
2866         ;; during a recursive-edit
2867         edebug-inside-windows
2868
2869         (edebug-outside-map (current-local-map))
2870
2871         (edebug-outside-standard-output standard-output)
2872         (edebug-outside-standard-input standard-input)
2873         (edebug-outside-defining-kbd-macro defining-kbd-macro)
2874
2875         (edebug-outside-last-command-char last-command-char)
2876         (edebug-outside-last-command last-command)
2877         (edebug-outside-this-command this-command)
2878         (edebug-outside-last-input-char last-input-char)
2879
2880         ;; XEmacs:  added the boundp checks
2881         (edebug-outside-unread-command-char
2882          (and (boundp 'unread-command-char) unread-command-char))
2883         (edebug-outside-current-prefix-arg
2884          (and (boundp 'current-prefix-arg) current-prefix-arg))
2885
2886         (edebug-outside-last-input-event
2887          (and (boundp 'last-input-event) last-input-event))
2888         (edebug-outside-last-command-event
2889          (and (boundp 'last-command-event) last-command-event))
2890         (edebug-outside-unread-command-event
2891          (and (boundp 'unread-command-event) unread-command-event))
2892         (edebug-outside-unread-command-events
2893          (and (boundp 'unread-command-events) unread-command-events))
2894         (edebug-outside-last-event-frame
2895          (and (boundp 'last-event-frame) last-event-frame))
2896         (edebug-outside-last-nonmenu-event
2897          (and (boundp 'last-nonmenu-event) last-nonmenu-event))
2898         (edebug-outside-track-mouse
2899          (and (boundp 'track-mouse) track-mouse))
2900         )
2901
2902     (unwind-protect
2903         (let (
2904               ;; Declare global values local but using the same global value.
2905               ;; We could set these to the values for previous edebug call.
2906               (last-command-char last-command-char)
2907               (last-command last-command)
2908               (this-command this-command)
2909               (last-input-char last-input-char)
2910
2911               ;; Assume no edebug command sets unread-command-char.
2912               (unread-command-char -1)
2913               (current-prefix-arg nil)
2914
2915               ;; More for Emacs 19
2916               (last-input-event nil)
2917               (last-command-event nil)
2918               (unread-command-event nil)        ; XEmacs addition
2919               (unread-command-events nil)
2920               (last-event-frame nil)
2921               (last-nonmenu-event nil)
2922               (track-mouse nil)
2923
2924               ;; Bind again to outside values.
2925               (debug-on-error edebug-outside-debug-on-error)
2926               (debug-on-quit edebug-outside-debug-on-quit)
2927
2928               ;; Don't keep defining a kbd macro.
2929               (defining-kbd-macro
2930                 (if edebug-continue-kbd-macro defining-kbd-macro))
2931
2932               ;; others??
2933               )
2934
2935           (zmacs-deactivate-region)    ; XEmacs addition
2936           (if (and (eq edebug-execution-mode 'go)
2937                    (not (memq edebug-arg-mode '(after error))))
2938               (message "Break"))
2939
2940           (setq buffer-read-only t)
2941           (setq signal-hook-function nil)
2942
2943           (edebug-mode)
2944           (unwind-protect
2945               (recursive-edit)          ;  <<<<<<<<<< Recursive edit
2946
2947             ;; Do the following, even if quit occurs.
2948             (setq signal-hook-function 'edebug-signal)
2949             (if edebug-backtrace-buffer
2950                 (kill-buffer edebug-backtrace-buffer))
2951             ;; Could be an option to keep eval display up.
2952             (if edebug-eval-buffer (kill-buffer edebug-eval-buffer))
2953
2954             ;; Remember selected-window after recursive-edit.
2955             ;;      (setq edebug-inside-window (selected-window))
2956
2957             (set-match-data edebug-outside-match-data)
2958
2959             ;; Recursive edit may have changed buffers,
2960             ;; so set it back before exiting let.
2961             (if (buffer-name edebug-buffer) ; if it still exists
2962                 (progn
2963                   (set-buffer edebug-buffer)
2964                   (if (memq edebug-execution-mode '(go Go-nonstop))
2965                       (edebug-overlay-arrow))
2966                   (setq buffer-read-only edebug-buffer-read-only)
2967                   (use-local-map edebug-outside-map)
2968                   )
2969               ;; gotta have a buffer to let its buffer local variables be set
2970               (get-buffer-create " bogus edebug buffer"))
2971             ));; inner let
2972
2973       ;; Reset global vars to outside values, in case they have been changed.
2974       (setq
2975        last-command-char edebug-outside-last-command-char
2976        last-command-event edebug-outside-last-command-event
2977        last-command edebug-outside-last-command
2978        this-command edebug-outside-this-command
2979        unread-command-char edebug-outside-unread-command-char
2980        unread-command-event edebug-outside-unread-command-event ; XEmacs
2981        unread-command-events edebug-outside-unread-command-events
2982        current-prefix-arg edebug-outside-current-prefix-arg
2983        last-input-char edebug-outside-last-input-char
2984        last-input-event edebug-outside-last-input-event
2985        last-event-frame edebug-outside-last-event-frame
2986        last-nonmenu-event edebug-outside-last-nonmenu-event
2987        track-mouse edebug-outside-track-mouse
2988
2989        standard-output edebug-outside-standard-output
2990        standard-input edebug-outside-standard-input
2991        defining-kbd-macro edebug-outside-defining-kbd-macro
2992        ))
2993     ))
2994
2995
2996 ;;; Display related functions
2997
2998 (defun edebug-adjust-window (old-start)
2999   ;; If pos is not visible, adjust current window to fit following context.
3000 ;;;  (message "window: %s old-start: %s window-start: %s pos: %s"
3001 ;;;        (selected-window) old-start (window-start) (point)) (sit-for 5)
3002   (if (not (pos-visible-in-window-p))
3003       (progn
3004         ;; First try old-start
3005         (if old-start
3006             (set-window-start (selected-window) old-start))
3007         (if (not (pos-visible-in-window-p))
3008             (progn
3009 ;;      (message "resetting window start") (sit-for 2)
3010         (set-window-start
3011          (selected-window)
3012          (save-excursion
3013            (forward-line
3014             (if (< (point) (window-start)) -1   ; one line before if in back
3015               (- (/ (window-height) 2)) ; center the line moving forward
3016               ))
3017            (beginning-of-line)
3018            (point)))))))
3019   (window-start))
3020
3021
3022
3023 (defconst edebug-arrow-alist
3024   '((Continue-fast . "=")
3025     (Trace-fast . "-")
3026     (continue . ">")
3027     (trace . "->")
3028     (step . "=>")
3029     (next . "=>")
3030     (go . "<>")
3031     (Go-nonstop . "..")  ; not used
3032     )
3033   "Association list of arrows for each edebug mode.")
3034
3035 (defun edebug-overlay-arrow ()
3036   ;; Set up the overlay arrow at beginning-of-line in current buffer.
3037   ;; The arrow string is derived from edebug-arrow-alist and
3038   ;; edebug-execution-mode.
3039   (let ((pos (save-excursion (beginning-of-line) (point))))
3040     (setq overlay-arrow-string
3041           (cdr (assq edebug-execution-mode edebug-arrow-alist)))
3042     (setq overlay-arrow-position (make-marker))
3043     (set-marker overlay-arrow-position pos (current-buffer))))
3044
3045
3046 (defun edebug-toggle-save-all-windows ()
3047   "Toggle the saving and restoring of all windows.
3048 Also, each time you toggle it on, the inside and outside window
3049 configurations become the same as the current configuration."
3050   (interactive)
3051   (setq edebug-save-windows (not edebug-save-windows))
3052   (if edebug-save-windows
3053       (setq edebug-inside-windows
3054             (setq edebug-outside-windows
3055                   (edebug-current-windows
3056                    edebug-save-windows))))
3057   (message "Window saving is %s for all windows."
3058            (if edebug-save-windows "on" "off")))
3059
3060 (defmacro edebug-changing-windows (&rest body)
3061   `(let ((window (selected-window)))
3062      (setq edebug-inside-windows (edebug-current-windows t))
3063      (edebug-set-windows edebug-outside-windows)
3064      ,@body;; Code to change edebug-save-windows
3065      (setq edebug-outside-windows (edebug-current-windows
3066                                    edebug-save-windows))
3067      ;; Problem: what about outside windows that are deleted inside?
3068      (edebug-set-windows edebug-inside-windows)))
3069
3070 (defun edebug-toggle-save-selected-window ()
3071   "Toggle the saving and restoring of the selected window.
3072 Also, each time you toggle it on, the inside and outside window
3073 configurations become the same as the current configuration."
3074   (interactive)
3075   (cond
3076    ((eq t edebug-save-windows)
3077     ;; Save all outside windows except the selected one.
3078     ;; Remove (selected-window) from outside-windows.
3079     (edebug-changing-windows
3080      (setq edebug-save-windows (delq window (edebug-window-list)))))
3081
3082    ((memq (selected-window) edebug-save-windows)
3083     (setq edebug-outside-windows
3084           (delq (assq (selected-window) edebug-outside-windows)
3085                 edebug-outside-windows))
3086     (setq edebug-save-windows
3087           (delq (selected-window) edebug-save-windows)))
3088    (t                                   ; Save a new window.
3089     (edebug-changing-windows
3090      (setq edebug-save-windows (cons window edebug-save-windows)))))
3091
3092   (message "Window saving is %s for %s."
3093            (if (memq (selected-window) edebug-save-windows)
3094                "on" "off")
3095            (selected-window)))
3096
3097 (defun edebug-toggle-save-windows (arg)
3098   "Toggle the saving and restoring of windows.
3099 With prefix, toggle for just the selected window.
3100 Otherwise, toggle for all windows."
3101   (interactive "P")
3102   (if arg
3103       (edebug-toggle-save-selected-window)
3104     (edebug-toggle-save-all-windows)))
3105
3106
3107 (defun edebug-where ()
3108   "Show the debug windows and where we stopped in the program."
3109   (interactive)
3110   (if (not edebug-active)
3111       (error "Edebug is not active"))
3112   ;; Restore the window configuration to what it last was inside.
3113   ;; But it is not always set.   - experiment
3114   ;;(if edebug-inside-windows
3115   ;;  (edebug-set-windows edebug-inside-windows))
3116   (edebug-pop-to-buffer edebug-buffer)
3117   (goto-char edebug-point))
3118
3119 (defun edebug-view-outside ()
3120   "Change to the outside window configuration."
3121   (interactive)
3122   (if (not edebug-active)
3123       (error "Edebug is not active"))
3124   (setq edebug-inside-windows
3125         (edebug-current-windows edebug-save-windows))
3126   (edebug-set-windows edebug-outside-windows)
3127   (goto-char edebug-outside-point)
3128   (message "Window configuration outside of Edebug.  Return with %s"
3129            (substitute-command-keys "\\<global-map>\\[edebug-where]")))
3130
3131
3132 (defun edebug-bounce-point (arg)
3133   "Bounce the point in the outside current buffer.
3134 If prefix arg is supplied, sit for that many seconds before returning.
3135 The default is one second."
3136   (interactive "p")
3137   (if (not edebug-active)
3138       (error "Edebug is not active"))
3139   (save-excursion
3140     ;; If the buffer's currently displayed, avoid set-window-configuration.
3141     (save-window-excursion
3142       (edebug-pop-to-buffer edebug-outside-buffer)
3143       (goto-char edebug-outside-point)
3144       (message "Current buffer: %s Point: %s Mark: %s"
3145                (current-buffer) (point)
3146                (if (marker-buffer (edebug-mark-marker))
3147                    (marker-position (edebug-mark-marker)) "<not set>"))
3148       (edebug-sit-for arg)
3149       (edebug-pop-to-buffer edebug-buffer (car edebug-window-data)))))
3150
3151
3152 ;; Joe Wells, here is a start at your idea of adding a buffer to the internal
3153 ;; display list.  Still need to use this list in edebug-display.
3154
3155 '(defvar edebug-display-buffer-list nil
3156   "List of buffers that edebug will display when it is active.")
3157
3158 '(defun edebug-display-buffer (buffer)
3159   "Toggle display of a buffer inside of edebug."
3160   (interactive "bBuffer: ")
3161   (let ((already-displaying (memq buffer edebug-display-buffer-list)))
3162     (setq edebug-display-buffer-list
3163           (if already-displaying
3164               (delq buffer edebug-display-buffer-list)
3165             (cons buffer edebug-display-buffer-list)))
3166     (message "Displaying %s %s" buffer
3167              (if already-displaying "off" "on"))))
3168
3169 ;;; Breakpoint related functions
3170
3171 (defun edebug-find-stop-point ()
3172   ;; Return (function . index) of the nearest edebug stop point.
3173   (let* ((edebug-def-name (edebug-form-data-symbol))
3174          (edebug-data
3175            (let ((data (get edebug-def-name 'edebug)))
3176              (if (or (null data) (markerp data))
3177                  (error "%s is not instrumented for Edebug" edebug-def-name))
3178              data))  ; we could do it automatically, if data is a marker.
3179          ;; pull out parts of edebug-data.
3180          (edebug-def-mark (car edebug-data))
3181          ;; (edebug-breakpoints (car (cdr edebug-data)))
3182
3183          (offset-vector (nth 2 edebug-data))
3184          (offset (- (save-excursion
3185                       (if (looking-at "[ \t]")
3186                           ;; skip backwards until non-whitespace, or bol
3187                           (skip-chars-backward " \t"))
3188                       (point))
3189                     edebug-def-mark))
3190          len i)
3191     ;; the offsets are in order so we can do a linear search
3192     (setq len (length offset-vector))
3193     (setq i 0)
3194     (while (and (< i len) (> offset (aref offset-vector i)))
3195       (setq i (1+ i)))
3196     (if (and (< i len)
3197              (<= offset (aref offset-vector i)))
3198         ;; return the relevant info
3199         (cons edebug-def-name i)
3200       (message "Point is not on an expression in %s."
3201                edebug-def-name)
3202       )))
3203
3204
3205 (defun edebug-next-breakpoint ()
3206   "Move point to the next breakpoint, or first if none past point."
3207   (interactive)
3208   (let ((edebug-stop-point (edebug-find-stop-point)))
3209     (if edebug-stop-point
3210         (let* ((edebug-def-name (car edebug-stop-point))
3211                (index (cdr edebug-stop-point))
3212                (edebug-data (get edebug-def-name 'edebug))
3213
3214                ;; pull out parts of edebug-data
3215                (edebug-def-mark (car edebug-data))
3216                (edebug-breakpoints (car (cdr edebug-data)))
3217                (offset-vector (nth 2 edebug-data))
3218                breakpoint)
3219           (if (not edebug-breakpoints)
3220               (message "No breakpoints in this function.")
3221             (let ((breaks edebug-breakpoints))
3222               (while (and breaks
3223                           (<= (car (car breaks)) index))
3224                 (setq breaks (cdr breaks)))
3225               (setq breakpoint
3226                     (if breaks
3227                         (car breaks)
3228                       ;; goto the first breakpoint
3229                       (car edebug-breakpoints)))
3230               (goto-char (+ edebug-def-mark
3231                             (aref offset-vector (car breakpoint))))
3232
3233               (message "%s"
3234                        (concat (if (nth 2 breakpoint)
3235                                    "Temporary " "")
3236                                (if (car (cdr breakpoint))
3237                                    (format "Condition: %s"
3238                                            (edebug-safe-prin1-to-string
3239                                             (car (cdr breakpoint))))
3240                                  "")))
3241               ))))))
3242
3243
3244 (defun edebug-modify-breakpoint (flag &optional condition temporary)
3245   "Modify the breakpoint for the form at point or after it according
3246 to FLAG: set if t, clear if nil.  Then move to that point.
3247 If CONDITION or TEMPORARY are non-nil, add those attributes to
3248 the breakpoint.  "
3249   (let ((edebug-stop-point (edebug-find-stop-point)))
3250     (if edebug-stop-point
3251         (let* ((edebug-def-name (car edebug-stop-point))
3252                (index (cdr edebug-stop-point))
3253                (edebug-data (get edebug-def-name 'edebug))
3254
3255                ;; pull out parts of edebug-data
3256                (edebug-def-mark (car edebug-data))
3257                (edebug-breakpoints (car (cdr edebug-data)))
3258                (offset-vector (nth 2 edebug-data))
3259                present)
3260           ;; delete it either way
3261           (setq present (assq index edebug-breakpoints))
3262           (setq edebug-breakpoints (delq present edebug-breakpoints))
3263           (if flag
3264               (progn
3265                 ;; add it to the list and resort
3266                 (setq edebug-breakpoints
3267                       (edebug-sort-alist
3268                        (cons
3269                         (list index condition temporary)
3270                         edebug-breakpoints) '<))
3271                 (if condition
3272                     (message "Breakpoint set in %s with condition: %s"
3273                              edebug-def-name condition)
3274                   (message "Breakpoint set in %s" edebug-def-name)))
3275             (if present
3276                 (message "Breakpoint unset in %s" edebug-def-name)
3277               (message "No breakpoint here")))
3278
3279           (setcar (cdr edebug-data) edebug-breakpoints)
3280           (goto-char (+ edebug-def-mark (aref offset-vector index)))
3281           ))))
3282
3283 (defun edebug-set-breakpoint (arg)
3284   "Set the breakpoint of nearest sexp.
3285 With prefix argument, make it a temporary breakpoint."
3286   (interactive "P")
3287   (edebug-modify-breakpoint t nil arg))
3288
3289 (defun edebug-unset-breakpoint ()
3290   "Clear the breakpoint of nearest sexp."
3291   (interactive)
3292   (edebug-modify-breakpoint nil))
3293
3294
3295 (defun edebug-set-global-break-condition (expression)
3296   (interactive (list (read-minibuffer
3297                       "Global Condition: "
3298                       (format "%s" edebug-global-break-condition))))
3299   (setq edebug-global-break-condition expression))
3300
3301
3302 ;;; Mode switching functions
3303
3304 (defun edebug-set-mode (mode shortmsg msg)
3305   ;; Set the edebug mode to MODE.
3306   ;; Display SHORTMSG, or MSG if not within edebug.
3307   (if (eq (1+ edebug-recursion-depth) (recursion-depth))
3308       (progn
3309         (setq edebug-execution-mode mode)
3310         (message shortmsg)
3311         ;; Continue execution
3312         (exit-recursive-edit))
3313     ;; This is not terribly useful!!
3314     (setq edebug-next-execution-mode mode)
3315     (message msg)))
3316
3317
3318 (defalias 'edebug-step-through-mode 'edebug-step-mode)
3319
3320 (defun edebug-step-mode ()
3321   "Proceed to next stop point."
3322   (interactive)
3323   (edebug-set-mode 'step "" "Edebug will stop at next stop point."))
3324
3325 (defun edebug-next-mode ()
3326   "Proceed to next `after' stop point."
3327   (interactive)
3328   (edebug-set-mode 'next "" "Edebug will stop after next eval."))
3329
3330 (defun edebug-go-mode (arg)
3331   "Go, evaluating until break.
3332 With prefix ARG, set temporary break at current point and go."
3333   (interactive "P")
3334   (if arg
3335       (edebug-set-breakpoint t))
3336   (edebug-set-mode 'go "Go..." "Edebug will go until break."))
3337
3338 (defun edebug-Go-nonstop-mode ()
3339   "Go, evaluating without debugging."
3340   (interactive)
3341   (edebug-set-mode 'Go-nonstop "Go-Nonstop..."
3342                    "Edebug will not stop at breaks."))
3343
3344
3345 (defun edebug-trace-mode ()
3346   "Begin trace mode."
3347   (interactive)
3348   (edebug-set-mode 'trace "Tracing..." "Edebug will trace with pause."))
3349
3350 (defun edebug-Trace-fast-mode ()
3351   "Trace with no wait at each step."
3352   (interactive)
3353   (edebug-set-mode 'Trace-fast
3354                    "Trace fast..." "Edebug will trace without pause."))
3355
3356 (defun edebug-continue-mode ()
3357   "Begin continue mode."
3358   (interactive)
3359   (edebug-set-mode 'continue "Continue..."
3360                    "Edebug will pause at breakpoints."))
3361
3362 (defun edebug-Continue-fast-mode ()
3363   "Trace with no wait at each step."
3364   (interactive)
3365   (edebug-set-mode 'Continue-fast "Continue fast..."
3366                    "Edebug will stop and go at breakpoints."))
3367
3368 ;; ------------------------------------------------------------
3369 ;; The following use the mode changing commands and breakpoints.
3370
3371
3372 (defun edebug-goto-here ()
3373   "Proceed to this stop point."
3374   (interactive)
3375   (edebug-go-mode t))
3376
3377
3378 (defun edebug-stop ()
3379   "Stop execution and do not continue.
3380 Useful for exiting from trace or continue loop."
3381   (interactive)
3382   (message "Stop"))
3383
3384
3385 '(defun edebug-forward ()
3386   "Proceed to the exit of the next expression to be evaluated."
3387   (interactive)
3388   (edebug-set-mode
3389    'forward "Forward"
3390    "Edebug will stop after exiting the next expression."))
3391
3392
3393 (defun edebug-forward-sexp (arg)
3394   "Proceed from the current point to the end of the ARGth sexp ahead.
3395 If there are not ARG sexps ahead, then do edebug-step-out."
3396   (interactive "p")
3397   (condition-case nil
3398       (let ((parse-sexp-ignore-comments t))
3399         ;; Call forward-sexp repeatedly until done or failure.
3400         (forward-sexp arg)
3401         (edebug-go-mode t))
3402     (error
3403      (edebug-step-out)
3404      )))
3405
3406 (defun edebug-step-out ()
3407   "Proceed from the current point to the end of the containing sexp.
3408 If there is no containing sexp that is not the top level defun,
3409 go to the end of the last sexp, or if that is the same point, then step."
3410   (interactive)
3411   (condition-case nil
3412       (let ((parse-sexp-ignore-comments t))
3413         (up-list 1)
3414         (save-excursion
3415           ;; Is there still a containing expression?
3416           (up-list 1))
3417         (edebug-go-mode t))
3418     (error
3419      ;; At top level - 1, so first check if there are more sexps at this level.
3420      (let ((start-point (point)))
3421 ;;       (up-list 1)
3422        (down-list -1)
3423        (if (= (point) start-point)
3424            (edebug-step-mode)   ; No more at this level, so step.
3425          (edebug-go-mode t)
3426          )))))
3427
3428 (defun edebug-instrument-function (func)
3429   ;; Func should be a function symbol.
3430   ;; Return the function symbol, or nil if not instrumented.
3431   (let ((func-marker (get func 'edebug)))
3432     (cond
3433      ((markerp func-marker)
3434       ;; It is uninstrumented, so instrument it.
3435       (with-current-buffer (marker-buffer func-marker)
3436         (goto-char func-marker)
3437         (edebug-eval-top-level-form)
3438         func))
3439      ((consp func-marker)
3440       (message "%s is already instrumented." func)
3441       func)
3442      (t
3443       (let ((loc (find-function-noselect func)))
3444         (with-current-buffer (car loc)
3445           (goto-char (cdr loc))
3446           (edebug-eval-top-level-form)
3447           func))))))
3448
3449 (defun edebug-instrument-callee ()
3450   "Instrument the definition of the function or macro about to be called.
3451 Do this when stopped before the form or it will be too late.
3452 One side effect of using this command is that the next time the
3453 function or macro is called, Edebug will be called there as well."
3454   (interactive)
3455   (if (not (looking-at "\("))
3456       (error "You must be before a list form")
3457     (let ((func
3458            (save-excursion
3459              (down-list 1)
3460              (if (looking-at "\(")
3461                  (edebug-form-data-name
3462                   (edebug-get-form-data-entry (point)))
3463                (edebug-original-read (current-buffer))))))
3464       (edebug-instrument-function func))))
3465
3466
3467 (defun edebug-step-in ()
3468   "Step into the definition of the function or macro about to be called.
3469 This first does `edebug-instrument-callee' to ensure that it is
3470 instrumented.  Then it does `edebug-on-entry' and switches to `go' mode."
3471   (interactive)
3472   (let ((func (edebug-instrument-callee)))
3473     (if func
3474         (progn
3475           (edebug-on-entry func 'temp)
3476           (edebug-go-mode nil)))))
3477
3478 (defun edebug-on-entry (function &optional flag)
3479   "Cause Edebug to stop when FUNCTION is called.
3480 With prefix argument, make this temporary so it is automatically
3481 cancelled the first time the function is entered."
3482   (interactive "aEdebug on entry to: \nP")
3483   ;; Could store this in the edebug data instead.
3484   (put function 'edebug-on-entry (if flag 'temp t)))
3485
3486 (defun cancel-edebug-on-entry (function)
3487   (interactive "aEdebug on entry to: ")
3488   (put function 'edebug-on-entry nil))
3489
3490
3491 (if (not (fboundp 'edebug-original-debug-on-entry))
3492     (fset 'edebug-original-debug-on-entry (symbol-function 'debug-on-entry)))
3493 '(fset 'debug-on-entry 'edebug-debug-on-entry)  ;; Should we do this?
3494 ;; Also need edebug-cancel-debug-on-entry
3495
3496 '(defun edebug-debug-on-entry (function)
3497   "Request FUNCTION to invoke debugger each time it is called.
3498 If the user continues, FUNCTION's execution proceeds.
3499 Works by modifying the definition of FUNCTION,
3500 which must be written in Lisp, not predefined.
3501 Use `cancel-debug-on-entry' to cancel the effect of this command.
3502 Redefining FUNCTION also does that.
3503
3504 This version is from Edebug.  If the function is instrumented for
3505 Edebug, it calls `edebug-on-entry'."
3506   (interactive "aDebug on entry (to function): ")
3507   (let ((func-data (get function 'edebug)))
3508     (if (or (null func-data) (markerp func-data))
3509         (edebug-original-debug-on-entry function)
3510       (edebug-on-entry function))))
3511
3512
3513 (defun edebug-top-level-nonstop ()
3514   "Set mode to Go-nonstop, and exit to top-level.
3515 This is useful for exiting even if unwind-protect code may be executed."
3516   (interactive)
3517   (setq edebug-execution-mode 'Go-nonstop)
3518   (top-level))
3519
3520
3521 ;;(defun edebug-exit-out ()
3522 ;;  "Go until the current function exits."
3523 ;;  (interactive)
3524 ;;  (edebug-set-mode 'exiting "Exit..."))
3525
3526
3527 ;;; The following initial mode setting definitions are not used yet.
3528
3529 '(defconst edebug-initial-mode-alist
3530   '((edebug-Continue-fast . Continue-fast)
3531     (edebug-Trace-fast . Trace-fast)
3532     (edebug-continue . continue)
3533     (edebug-trace . trace)
3534     (edebug-go . go)
3535     (edebug-step-through . step)
3536     (edebug-Go-nonstop . Go-nonstop)
3537     )
3538   "Association list between commands and the modes they set.")
3539
3540
3541 '(defun edebug-set-initial-mode ()
3542   "Ask for the initial mode of the enclosing function.
3543 The mode is requested via the key that would be used to set the mode in
3544 edebug-mode."
3545   (interactive)
3546   (let* ((this-function (edebug-which-function))
3547          (keymap (if (eq edebug-mode-map (current-local-map))
3548                      edebug-mode-map))
3549          (old-mode (or (get this-function 'edebug-initial-mode)
3550                        edebug-initial-mode))
3551          (key (read-key-sequence
3552                (format
3553                 "Change initial edebug mode for %s from %s (%s) to (enter key): "
3554                        this-function
3555                        old-mode
3556                        (where-is-internal
3557                         (car (rassq old-mode edebug-initial-mode-alist))
3558                         keymap 'firstonly
3559                         ))))
3560          (mode (cdr (assq (key-binding key) edebug-initial-mode-alist)))
3561          )
3562     (if (and mode
3563              (or (get this-function 'edebug-initial-mode)
3564                  (not (eq mode edebug-initial-mode))))
3565         (progn
3566           (put this-function 'edebug-initial-mode mode)
3567           (message "Initial mode for %s is now: %s"
3568                    this-function mode))
3569       (error "Key must map to one of the mode changing commands")
3570       )))
3571
3572 ;;; Evaluation of expressions
3573
3574 (def-edebug-spec edebug-outside-excursion t)
3575
3576 (defmacro edebug-outside-excursion (&rest body)
3577   "Evaluate an expression list in the outside context.
3578 Return the result of the last expression."
3579   `(save-excursion                      ; of current-buffer
3580      (if edebug-save-windows
3581          (progn
3582            ;; After excursion, we will
3583            ;; restore to current window configuration.
3584            (setq edebug-inside-windows
3585                  (edebug-current-windows edebug-save-windows))
3586            ;; Restore outside windows.
3587            (edebug-set-windows edebug-outside-windows)))
3588
3589      (set-buffer edebug-buffer)         ; why?
3590      ;; (use-local-map edebug-outside-map)
3591      (set-match-data edebug-outside-match-data)
3592      ;; Restore outside context.
3593      (let (;; (edebug-inside-map (current-local-map)) ;; restore map??
3594            (last-command-char edebug-outside-last-command-char)
3595            (last-command-event edebug-outside-last-command-event)
3596            (last-command edebug-outside-last-command)
3597            (this-command edebug-outside-this-command)
3598            (unread-command-char edebug-outside-unread-command-char)
3599            (unread-command-event edebug-outside-unread-command-event) ; XEmacs
3600            (unread-command-events edebug-outside-unread-command-events)
3601            (current-prefix-arg edebug-outside-current-prefix-arg)
3602            (last-input-char edebug-outside-last-input-char)
3603            (last-input-event edebug-outside-last-input-event)
3604            (last-event-frame edebug-outside-last-event-frame)
3605            (last-nonmenu-event edebug-outside-last-nonmenu-event)
3606            (track-mouse edebug-outside-track-mouse)
3607            (standard-output edebug-outside-standard-output)
3608            (standard-input edebug-outside-standard-input)
3609
3610            (executing-kbd-macro edebug-outside-executing-macro)
3611            (defining-kbd-macro edebug-outside-defining-kbd-macro)
3612            ;; Get the values out of the saved statuses.
3613            (pre-command-hook (cdr edebug-outside-pre-command-hook))
3614            (post-command-hook (cdr edebug-outside-post-command-hook))
3615
3616            ;; See edebug-display
3617            (overlay-arrow-position edebug-outside-o-a-p)
3618            (overlay-arrow-string edebug-outside-o-a-s)
3619            (cursor-in-echo-area edebug-outside-c-i-e-a)
3620            )
3621        (unwind-protect
3622            (save-excursion              ; of edebug-buffer
3623              (set-buffer edebug-outside-buffer)
3624              (goto-char edebug-outside-point)
3625              (if (marker-buffer (edebug-mark-marker))
3626                  (set-marker (edebug-mark-marker) edebug-outside-mark))
3627              ,@body)
3628
3629          ;; Back to edebug-buffer.  Restore rest of inside context.
3630          ;; (use-local-map edebug-inside-map)
3631          (if edebug-save-windows
3632              ;; Restore inside windows.
3633              (edebug-set-windows edebug-inside-windows))
3634
3635          ;; Save values that may have been changed.
3636          (setq
3637           edebug-outside-last-command-char last-command-char
3638           edebug-outside-last-command-event last-command-event
3639           edebug-outside-last-command last-command
3640           edebug-outside-this-command this-command
3641           edebug-outside-unread-command-char unread-command-char
3642           edebug-outside-unread-command-event unread-command-event ; XEmacs
3643           edebug-outside-unread-command-events unread-command-events
3644           edebug-outside-current-prefix-arg current-prefix-arg
3645           edebug-outside-last-input-char last-input-char
3646           edebug-outside-last-input-event last-input-event
3647           edebug-outside-last-event-frame last-event-frame
3648           edebug-outside-last-nonmenu-event last-nonmenu-event
3649           edebug-outside-track-mouse track-mouse
3650           edebug-outside-standard-output standard-output
3651           edebug-outside-standard-input standard-input
3652
3653           edebug-outside-executing-macro executing-kbd-macro
3654           edebug-outside-defining-kbd-macro defining-kbd-macro
3655
3656           edebug-outside-o-a-p overlay-arrow-position
3657           edebug-outside-o-a-s overlay-arrow-string
3658           edebug-outside-c-i-e-a cursor-in-echo-area
3659           )
3660
3661          ;; Restore the outside saved values; don't alter
3662          ;; the outside binding loci.
3663          (setcdr edebug-outside-pre-command-hook pre-command-hook)
3664          (setcdr edebug-outside-post-command-hook post-command-hook)
3665
3666          ))                             ; let
3667      ))
3668
3669 (defvar cl-debug-env nil) ;; defined in cl; non-nil when lexical env used.
3670
3671 (defun edebug-eval (edebug-expr)
3672   ;; Are there cl lexical variables active?
3673   (if cl-debug-env
3674       (eval (cl-macroexpand-all edebug-expr cl-debug-env))
3675     (eval edebug-expr)))
3676
3677 (defun edebug-safe-eval (edebug-expr)
3678   ;; Evaluate EXPR safely.
3679   ;; If there is an error, a string is returned describing the error.
3680   (condition-case edebug-err
3681       (edebug-eval edebug-expr)
3682     (error (edebug-format "%s: %s"  ;; could
3683                           (get (car edebug-err) 'error-message)
3684                           (car (cdr edebug-err))))))
3685
3686 ;;; Printing
3687
3688 ;; Replace printing functions.
3689
3690 ;; obsolete names
3691 (defalias 'edebug-install-custom-print-funcs 'edebug-install-custom-print)
3692 (defalias 'edebug-reset-print-funcs 'edebug-uninstall-custom-print)
3693 (defalias 'edebug-uninstall-custom-print-funcs 'edebug-uninstall-custom-print)
3694
3695 (defun edebug-install-custom-print ()
3696   "Replace print functions used by Edebug with custom versions."
3697   ;; Modifying the custom print functions, or changing print-length,
3698   ;; print-level, print-circle, custom-print-list or custom-print-vector
3699   ;; have immediate effect.
3700   (interactive)
3701   (require 'cust-print)
3702   (defalias 'edebug-prin1 'custom-prin1)
3703   (defalias 'edebug-print 'custom-print)
3704   (defalias 'edebug-prin1-to-string 'custom-prin1-to-string)
3705   (defalias 'edebug-format 'custom-format)
3706   (defalias 'edebug-message 'custom-message)
3707   "Installed")
3708
3709 (eval-and-compile
3710   (defun edebug-uninstall-custom-print ()
3711     "Replace edebug custom print functions with internal versions."
3712     (interactive)
3713     (defalias 'edebug-prin1 'prin1)
3714     (defalias 'edebug-print 'print)
3715     (defalias 'edebug-prin1-to-string 'prin1-to-string)
3716     (defalias 'edebug-format 'format)
3717     (defalias 'edebug-message 'message)
3718     "Uninstalled")
3719
3720   ;; Default print functions are the same as Emacs'.
3721   (edebug-uninstall-custom-print))
3722
3723
3724 (defun edebug-report-error (edebug-value)
3725   ;; Print an error message like command level does.
3726   ;; This also prints the error name if it has no error-message.
3727   (message "%s: %s"
3728            (or (get (car edebug-value) 'error-message)
3729                (format "peculiar error (%s)" (car edebug-value)))
3730            (mapconcat (function (lambda (edebug-arg)
3731                                   ;; continuing after an error may
3732                                   ;; complain about edebug-arg. why??
3733                                   (prin1-to-string edebug-arg)))
3734                       (cdr edebug-value) ", ")))
3735
3736 ;; Define here in case they are not already defined.
3737 (defvar print-level nil)
3738 (defvar print-circle nil)
3739 (defvar print-readably) ;; defined by XEmacs
3740 ;; Alternatively, we could change the definition of
3741 ;; edebug-safe-prin1-to-string to only use these if defined.
3742
3743 (defun edebug-safe-prin1-to-string (value)
3744   (let ((print-escape-newlines t)
3745         (print-length (or edebug-print-length print-length))
3746         (print-level (or edebug-print-level print-level))
3747         (print-circle (or edebug-print-circle print-circle))
3748         (print-readably nil)) ;; XEmacs uses this.
3749     (edebug-prin1-to-string value)))
3750
3751 (defun edebug-compute-previous-result (edebug-previous-value)
3752   (setq edebug-previous-result
3753         (if (and (integerp edebug-previous-value)
3754                  (< edebug-previous-value 256)
3755                  (>= edebug-previous-value 0))
3756             (format "Result: %s = %s" edebug-previous-value
3757                     (single-key-description edebug-previous-value))
3758           (if edebug-unwrap-results
3759               (setq edebug-previous-value 
3760                     (edebug-unwrap* edebug-previous-value)))
3761           (concat "Result: " 
3762                   (edebug-safe-prin1-to-string edebug-previous-value)))))
3763
3764 (defun edebug-previous-result ()
3765   "Print the previous result."
3766   (interactive)
3767   (message "%s" edebug-previous-result))
3768
3769 ;;; Read, Eval and Print
3770
3771 (defun edebug-eval-expression (edebug-expr)
3772   "Evaluate an expression in the outside environment.
3773 If interactive, prompt for the expression.
3774 Print result in minibuffer."
3775   (interactive (list (read-from-minibuffer
3776                       "Eval: " nil read-expression-map t
3777                       'read-expression-history)))
3778   (princ
3779    (edebug-outside-excursion
3780     (setq values (cons (edebug-eval edebug-expr) values))
3781     (edebug-safe-prin1-to-string (car values)))))
3782
3783 (defun edebug-eval-last-sexp ()
3784   "Evaluate sexp before point in the outside environment; value in minibuffer."
3785   (interactive)
3786   (edebug-eval-expression (edebug-last-sexp)))
3787
3788 (defun edebug-eval-print-last-sexp ()
3789   "Evaluate sexp before point in the outside environment; insert the value.
3790 This prints the value into current buffer."
3791   (interactive)
3792   (let* ((edebug-form (edebug-last-sexp))
3793          (edebug-result-string
3794           (edebug-outside-excursion
3795            (edebug-safe-prin1-to-string (edebug-safe-eval edebug-form))))
3796          (standard-output (current-buffer)))
3797     (princ "\n")
3798     ;; princ the string to get rid of quotes.
3799     (princ edebug-result-string)
3800     (princ "\n")
3801     ))
3802
3803 ;;; Edebug Minor Mode
3804
3805 (defvar gud-inhibit-global-bindings
3806   "*Non-nil means don't do global rebindings of C-x C-a subcommands.")
3807
3808 ;; Global GUD bindings for all emacs-lisp-mode buffers.
3809 (unless gud-inhibit-global-bindings
3810   (define-key emacs-lisp-mode-map "\C-x\C-a\C-s" 'edebug-step-mode)
3811   (define-key emacs-lisp-mode-map "\C-x\C-a\C-n" 'edebug-next-mode)
3812   (define-key emacs-lisp-mode-map "\C-x\C-a\C-c" 'edebug-go-mode)
3813   (define-key emacs-lisp-mode-map "\C-x\C-a\C-l" 'edebug-where))
3814
3815 (defvar edebug-mode-map
3816   (let ((map (copy-keymap emacs-lisp-mode-map)))
3817     ;; control
3818     (define-key map " " 'edebug-step-mode)
3819     (define-key map "n" 'edebug-next-mode)
3820     (define-key map "g" 'edebug-go-mode)
3821     (define-key map "G" 'edebug-Go-nonstop-mode)
3822     (define-key map "t" 'edebug-trace-mode)
3823     (define-key map "T" 'edebug-Trace-fast-mode)
3824     (define-key map "c" 'edebug-continue-mode)
3825     (define-key map "C" 'edebug-Continue-fast-mode)
3826
3827     ;;(define-key map "f" 'edebug-forward) not implemented
3828     (define-key map "f" 'edebug-forward-sexp)
3829     (define-key map "h" 'edebug-goto-here)
3830
3831     (define-key map "I" 'edebug-instrument-callee)
3832     (define-key map "i" 'edebug-step-in)
3833     (define-key map "o" 'edebug-step-out)
3834
3835     ;; quitting and stopping
3836     (define-key map "q" 'top-level)
3837     (define-key map "Q" 'edebug-top-level-nonstop)
3838     (define-key map "a" 'abort-recursive-edit)
3839     (define-key map "S" 'edebug-stop)
3840
3841     ;; breakpoints
3842     (define-key map "b" 'edebug-set-breakpoint)
3843     (define-key map "u" 'edebug-unset-breakpoint)
3844     (define-key map "B" 'edebug-next-breakpoint)
3845     (define-key map "x" 'edebug-set-conditional-breakpoint)
3846     (define-key map "X" 'edebug-set-global-break-condition)
3847
3848     ;; evaluation
3849     (define-key map "r" 'edebug-previous-result)
3850     (define-key map "e" 'edebug-eval-expression)
3851     (define-key map "\C-x\C-e" 'edebug-eval-last-sexp)
3852     (define-key map "E" 'edebug-visit-eval-list)
3853
3854     ;; views
3855     (define-key map "w" 'edebug-where)
3856     (define-key map "v" 'edebug-view-outside) ;; maybe obsolete??
3857     (define-key map "p" 'edebug-bounce-point)
3858     (define-key map "P" 'edebug-view-outside) ;; same as v
3859     (define-key map "W" 'edebug-toggle-save-windows)
3860
3861     ;; misc
3862     (define-key map "?" 'edebug-help)
3863     (define-key map "d" 'edebug-backtrace)
3864
3865     (define-key map "-" 'negative-argument)
3866
3867     ;; statistics
3868     (define-key map "=" 'edebug-temp-display-freq-count)
3869
3870     ;; GUD bindings
3871     (define-key map "\C-c\C-s" 'edebug-step-mode)
3872     (define-key map "\C-c\C-n" 'edebug-next-mode)
3873     (define-key map "\C-c\C-c" 'edebug-go-mode)
3874
3875     (define-key map "\C-x " 'edebug-set-breakpoint)
3876     (define-key map "\C-c\C-d" 'edebug-unset-breakpoint)
3877     (define-key map "\C-c\C-t"
3878       #'(lambda () (interactive) (edebug-set-breakpoint t)))
3879     (define-key map "\C-c\C-l" 'edebug-where)
3880     map))
3881
3882 ;; Autoloading these global bindings doesn't make sense because
3883 ;; they cannot be used anyway unless Edebug is already loaded and active.
3884
3885 (defvar global-edebug-prefix "\^XX"
3886   "Prefix key for global edebug commands, available from any buffer.")
3887
3888 (defvar global-edebug-map
3889   (let ((map (make-sparse-keymap)))
3890
3891     (define-key map " " 'edebug-step-mode)
3892     (define-key map "g" 'edebug-go-mode)
3893     (define-key map "G" 'edebug-Go-nonstop-mode)
3894     (define-key map "t" 'edebug-trace-mode)
3895     (define-key map "T" 'edebug-Trace-fast-mode)
3896     (define-key map "c" 'edebug-continue-mode)
3897     (define-key map "C" 'edebug-Continue-fast-mode)
3898
3899     ;; breakpoints
3900     (define-key map "b" 'edebug-set-breakpoint)
3901     (define-key map "u" 'edebug-unset-breakpoint)
3902     (define-key map "x" 'edebug-set-conditional-breakpoint)
3903     (define-key map "X" 'edebug-set-global-break-condition)
3904
3905     ;; views
3906     (define-key map "w" 'edebug-where)
3907     (define-key map "W" 'edebug-toggle-save-windows)
3908
3909     ;; quitting
3910     (define-key map "q" 'top-level)
3911     (define-key map "Q" 'edebug-top-level-nonstop)
3912     (define-key map "a" 'abort-recursive-edit)
3913
3914     ;; statistics
3915     (define-key map "=" 'edebug-display-freq-count)
3916     map)
3917   "Global map of edebug commands, available from any buffer.")
3918
3919 (global-unset-key global-edebug-prefix)
3920 (global-set-key global-edebug-prefix global-edebug-map)
3921
3922
3923 (defun edebug-help ()
3924   (interactive)
3925   (describe-function 'edebug-mode))
3926
3927 (defun edebug-mode ()
3928   "Mode for Emacs Lisp buffers while in Edebug.
3929
3930 In addition to all Emacs Lisp commands (except those that modify the
3931 buffer) there are local and global key bindings to several Edebug
3932 specific commands.  E.g. `edebug-step-mode' is bound to \\[edebug-step-mode]
3933 in the Edebug buffer and \\<global-map>\\[edebug-step-mode] in any buffer.
3934
3935 Also see bindings for the eval list buffer, *edebug*.
3936
3937 The edebug buffer commands:
3938 \\{edebug-mode-map}
3939
3940 Global commands prefixed by `global-edebug-prefix':
3941 \\{global-edebug-map}
3942
3943 Options:
3944 edebug-setup-hook
3945 edebug-all-defs
3946 edebug-all-forms
3947 edebug-save-windows
3948 edebug-save-displayed-buffer-points
3949 edebug-initial-mode
3950 edebug-trace
3951 edebug-test-coverage
3952 edebug-continue-kbd-macro
3953 edebug-print-length
3954 edebug-print-level
3955 edebug-print-circle
3956 edebug-on-error
3957 edebug-on-quit
3958 edebug-on-signal
3959 edebug-unwrap-results
3960 edebug-global-break-condition
3961 "
3962   (use-local-map edebug-mode-map))
3963
3964 ;;; edebug eval list mode
3965
3966 ;; A list of expressions and their evaluations is displayed in *edebug*.
3967
3968 (defun edebug-eval-result-list ()
3969   "Return a list of evaluations of edebug-eval-list"
3970   ;; Assumes in outside environment.
3971   ;; Don't do any edebug things now.
3972   (let ((edebug-execution-mode 'Go-nonstop)
3973         (edebug-trace nil))
3974     (mapcar 'edebug-safe-eval edebug-eval-list)))
3975
3976 (defun edebug-eval-display-list (edebug-eval-result-list)
3977   ;; Assumes edebug-eval-buffer exists.
3978   (let ((edebug-eval-list-temp edebug-eval-list)
3979         (standard-output edebug-eval-buffer)
3980         (edebug-comment-line
3981          (format ";%s\n" (make-string (- (window-width) 2) ?-))))
3982     (set-buffer edebug-eval-buffer)
3983     (erase-buffer)
3984     (while edebug-eval-list-temp
3985       (prin1 (car edebug-eval-list-temp)) (terpri)
3986       (prin1 (car edebug-eval-result-list)) (terpri)
3987       (princ edebug-comment-line)
3988       (setq edebug-eval-list-temp (cdr edebug-eval-list-temp))
3989       (setq edebug-eval-result-list (cdr edebug-eval-result-list)))
3990     (edebug-pop-to-buffer edebug-eval-buffer)
3991     ))
3992
3993 (defun edebug-create-eval-buffer ()
3994   (if (not (and edebug-eval-buffer (buffer-name edebug-eval-buffer)))
3995       (progn
3996         (set-buffer (setq edebug-eval-buffer (get-buffer-create "*edebug*")))
3997         (edebug-eval-mode))))
3998
3999 ;; Should generalize this to be callable outside of edebug
4000 ;; with calls in user functions, e.g. (edebug-eval-display)
4001
4002 (defun edebug-eval-display (edebug-eval-result-list)
4003   "Display expressions and evaluations in EVAL-LIST.
4004 It modifies the context by popping up the eval display."
4005   (if edebug-eval-result-list
4006       (progn
4007         (edebug-create-eval-buffer)
4008         (edebug-eval-display-list edebug-eval-result-list)
4009         )))
4010
4011 (defun edebug-eval-redisplay ()
4012   "Redisplay eval list in outside environment.
4013 May only be called from within edebug-recursive-edit."
4014   (edebug-create-eval-buffer)
4015   (edebug-outside-excursion
4016    (edebug-eval-display-list (edebug-eval-result-list))
4017    ))
4018
4019 (defun edebug-visit-eval-list ()
4020   (interactive)
4021   (edebug-eval-redisplay)
4022   (edebug-pop-to-buffer edebug-eval-buffer))
4023
4024
4025 (defun edebug-update-eval-list ()
4026   "Replace the evaluation list with the sexps now in the eval buffer."
4027   (interactive)
4028   (let ((starting-point (point))
4029         new-list)
4030     (goto-char (point-min))
4031     ;; get the first expression
4032     (edebug-skip-whitespace)
4033     (if (not (eobp))
4034         (progn
4035           (forward-sexp 1)
4036           (setq new-list (cons (edebug-last-sexp) new-list))))
4037
4038     (while (re-search-forward "^;" nil t)
4039       (forward-line 1)
4040       (skip-chars-forward " \t\n\r")
4041       (if (and (/= ?\; (char-after))
4042                (not (eobp)))
4043           (progn
4044             (forward-sexp 1)
4045             (setq new-list (cons (edebug-last-sexp) new-list)))))
4046
4047     (setq edebug-eval-list (nreverse new-list))
4048     (edebug-eval-redisplay)
4049     (goto-char starting-point)))
4050
4051
4052 (defun edebug-delete-eval-item ()
4053   "Delete the item under point and redisplay."
4054   ;; could add arg to do repeatedly
4055   (interactive)
4056   (if (re-search-backward "^;" nil 'nofail)
4057       (forward-line 1))
4058   (delete-region
4059    (point) (progn (re-search-forward "^;" nil 'nofail)
4060                   (beginning-of-line)
4061                   (point)))
4062   (edebug-update-eval-list))
4063
4064
4065
4066 (defvar edebug-eval-mode-map nil
4067   "Keymap for Edebug Eval mode.  Superset of Lisp Interaction mode.")
4068
4069 (if edebug-eval-mode-map
4070     nil
4071   (setq edebug-eval-mode-map (copy-keymap lisp-interaction-mode-map))
4072
4073   (define-key edebug-eval-mode-map "\C-c\C-w" 'edebug-where)
4074   (define-key edebug-eval-mode-map "\C-c\C-d" 'edebug-delete-eval-item)
4075   (define-key edebug-eval-mode-map "\C-c\C-u" 'edebug-update-eval-list)
4076   (define-key edebug-eval-mode-map "\C-x\C-e" 'edebug-eval-last-sexp)
4077   (define-key edebug-eval-mode-map "\C-j" 'edebug-eval-print-last-sexp)
4078   )
4079
4080 (put 'edebug-eval-mode 'mode-class 'special)
4081
4082 (defun edebug-eval-mode ()
4083   "Mode for evaluation list buffer while in Edebug.
4084
4085 In addition to all Interactive Emacs Lisp commands there are local and
4086 global key bindings to several Edebug specific commands.  E.g.
4087 `edebug-step-mode' is bound to \\[edebug-step-mode] in the Edebug
4088 buffer and \\<global-map>\\[edebug-step-mode] in any buffer.
4089
4090 Eval list buffer commands:
4091 \\{edebug-eval-mode-map}
4092
4093 Global commands prefixed by global-edebug-prefix:
4094 \\{global-edebug-map}
4095 "
4096   (lisp-interaction-mode)
4097   (setq major-mode 'edebug-eval-mode)
4098   (setq mode-name "Edebug Eval")
4099   (use-local-map edebug-eval-mode-map))
4100
4101 ;;; Interface with standard debugger.
4102
4103 ;; (setq debugger 'edebug) ; to use the edebug debugger
4104 ;; (setq debugger 'debug)  ; use the standard debugger
4105
4106 ;; Note that debug and its utilities must be byte-compiled to work,
4107 ;; since they depend on the backtrace looking a certain way.  But
4108 ;; edebug is not dependent on this, yet.
4109
4110 (defun edebug (&optional edebug-arg-mode &rest debugger-args)
4111   "Replacement for debug.
4112 If we are running an edebugged function,
4113 show where we last were.  Otherwise call debug normally."
4114 ;;  (message "entered: %s  depth: %s  edebug-recursion-depth: %s"
4115 ;;         edebug-entered (recursion-depth) edebug-recursion-depth) (sit-for 1)
4116   (if (and edebug-entered  ; anything active?
4117            (eq (recursion-depth) edebug-recursion-depth))
4118       (let (;; Where were we before the error occurred?
4119             (edebug-offset-index (car edebug-offset-indices))
4120             ;; Bind variables required by edebug-display
4121             (edebug-value (car debugger-args))
4122             edebug-breakpoints
4123             edebug-break-data
4124             edebug-break-condition
4125             edebug-global-break
4126             (edebug-break (null edebug-arg-mode)) ;; if called explicitly
4127             )
4128         (edebug-display)
4129         (if (eq edebug-arg-mode 'error)
4130             nil
4131           edebug-value))
4132
4133     ;; Otherwise call debug normally.
4134     ;; Still need to remove extraneous edebug calls from stack.
4135     (apply 'debug edebug-arg-mode debugger-args)
4136     ))
4137
4138
4139 (defun edebug-backtrace ()
4140   "Display a non-working backtrace.  Better than nothing..."
4141   (interactive)
4142   (if (or (not edebug-backtrace-buffer)
4143           (null (buffer-name edebug-backtrace-buffer)))
4144       (setq edebug-backtrace-buffer
4145             (generate-new-buffer "*Backtrace*"))
4146     ;; else, could just display edebug-backtrace-buffer
4147     )
4148   (with-output-to-temp-buffer (buffer-name edebug-backtrace-buffer)
4149     (setq edebug-backtrace-buffer standard-output)
4150     (let ((print-escape-newlines t)
4151           (print-length 50)
4152           last-ok-point)
4153       (backtrace)
4154
4155       ;; Clean up the backtrace.
4156       ;; Not quite right for current edebug scheme.
4157       (set-buffer edebug-backtrace-buffer)
4158       (setq truncate-lines t)
4159       (goto-char (point-min))
4160       (setq last-ok-point (point))
4161       (if t (progn
4162
4163       ;; Delete interspersed edebug internals.
4164       (while (re-search-forward "^  \(?edebug" nil t)
4165         (beginning-of-line)
4166         (cond
4167          ((looking-at "^  \(edebug-after")
4168           ;; Previous lines may contain code, so just delete this line
4169           (setq last-ok-point (point))
4170           (forward-line 1)
4171           (delete-region last-ok-point (point)))
4172
4173          ((looking-at "^  edebug")
4174           (forward-line 1)
4175           (delete-region last-ok-point (point))
4176           )))
4177       )))))
4178
4179 \f
4180 ;;; Trace display
4181
4182 (defun edebug-trace-display (buf-name fmt &rest args)
4183   "In buffer BUF-NAME, display FMT and ARGS at the end and make it visible.
4184 The buffer is created if it does not exist.
4185 You must include newlines in FMT to break lines, but one newline is appended."
4186 ;; e.g.
4187 ;;       (edebug-trace-display "*trace-point*"
4188 ;;        "saving: point = %s  window-start = %s"
4189 ;;        (point) (window-start))
4190   (let* ((oldbuf (current-buffer))
4191          (selected-window (selected-window))
4192          (buffer (get-buffer-create buf-name))
4193          buf-window)
4194 ;;    (message "before pop-to-buffer") (sit-for 1)
4195     (edebug-pop-to-buffer buffer)
4196     (setq truncate-lines t)
4197     (setq buf-window (selected-window))
4198     (goto-char (point-max))
4199     (insert (apply 'edebug-format fmt args) "\n")
4200     ;; Make it visible.
4201     (vertical-motion (- 1 (window-height)))
4202     (set-window-start buf-window (point))
4203     (goto-char (point-max))
4204 ;;    (set-window-point buf-window (point))
4205 ;;    (edebug-sit-for 0)
4206     (bury-buffer buffer)
4207     (select-window selected-window)
4208     (set-buffer oldbuf))
4209   buf-name)
4210
4211
4212 (defun edebug-trace (fmt &rest args)
4213   "Convenience call to edebug-trace-display using edebug-trace-buffer"
4214   (apply 'edebug-trace-display edebug-trace-buffer fmt args))
4215
4216 \f
4217 ;;; Frequency count and coverage
4218
4219 (defun edebug-display-freq-count ()
4220   "Display the frequency count data for each line of the current definition.
4221 The frequency counts are inserted as comment lines after
4222 each line, and you can undo all insertions with one `undo' command.
4223
4224 The counts are inserted starting under the `(' before an expression
4225 or the `)' after an expression, or on the last char of a symbol.
4226 The counts are only displayed when they differ from previous counts on
4227 the same line.
4228
4229 If coverage is being tested, whenever all known results of an expression
4230 are `eq', the char `=' will be appended after the count
4231 for that expression.  Note that this is always the case for an
4232 expression only evaluated once.
4233
4234 To clear the frequency count and coverage data for a definition,
4235 reinstrument it."
4236   (interactive)
4237   (let* ((function (edebug-form-data-symbol))
4238          (counts (get function 'edebug-freq-count))
4239          (coverages (get function 'edebug-coverage))
4240          (data (get function 'edebug))
4241          (def-mark (car data))  ; mark at def start
4242          (edebug-points (nth 2 data))
4243          (i (1- (length edebug-points)))
4244          (last-index)
4245          (first-index)
4246          (start-of-line)
4247          (start-of-count-line)
4248          (last-count)
4249          )
4250     (save-excursion
4251       ;; Traverse in reverse order so offsets are correct.
4252       (while (<= 0 i)
4253         ;; Start at last expression in line.
4254         (goto-char (+ def-mark (aref edebug-points i)))
4255         (beginning-of-line)
4256         (setq start-of-line (- (point) def-mark)
4257               last-index i)
4258
4259         ;; Find all indexes on same line.
4260         (while (and (<= 0 (setq i (1- i)))
4261                     (<= start-of-line (aref edebug-points i))))
4262         ;; Insert all the indices for this line.
4263         (forward-line 1)
4264         (setq start-of-count-line (point)
4265               first-index i   ; really last index for line above this one.
4266               last-count -1)  ; cause first count to always appear.
4267         (insert ";#")
4268         ;; i == first-index still
4269         (while (<= (setq i (1+ i)) last-index)
4270           (let ((count (aref counts i))
4271                 (coverage (aref coverages i))
4272                 (col (save-excursion
4273                        (goto-char (+ (aref edebug-points i) def-mark))
4274                        (- (current-column)
4275                           (if (= ?\( (char-after)) 0 1)))))
4276             (insert (make-string
4277                      (max 0 (- col (- (point) start-of-count-line))) ?\ )
4278                     (if (and (< 0 count)
4279                              (not (memq coverage
4280                                         '(unknown ok-coverage))))
4281                         "=" "")
4282                     (if (= count last-count) "" (int-to-string count))
4283                     " ")
4284             (setq last-count count)))
4285         (insert "\n")
4286         (setq i first-index)))))
4287
4288 (defun edebug-temp-display-freq-count ()
4289   "Temporarily display the frequency count data for the current definition.
4290 It is removed when you hit any char."
4291   ;; This seems not to work with Emacs 18.59. It undoes too far.
4292   (interactive)
4293   (let ((buffer-read-only nil))
4294     (undo-boundary)
4295     (edebug-display-freq-count)
4296     (setq unread-command-char (read-char))
4297     (undo)))
4298
4299 \f
4300 ;;; Menus
4301
4302 (defun edebug-toggle (variable)
4303   (set variable (not (eval variable)))
4304   (message "%s: %s" variable (eval variable)))
4305
4306 ;; We have to require easymenu (even for Emacs 18) just so
4307 ;; the easy-menu-define macro call is compiled correctly.
4308 (require 'easymenu)
4309
4310 (defconst edebug-mode-menus
4311   '("Edebug"
4312      "----"  ; XEmacs
4313      ["Stop" edebug-stop t]
4314      ["Step" edebug-step-mode t]
4315      ["Next" edebug-next-mode t]
4316      ["Trace" edebug-trace-mode t]
4317      ["Trace Fast" edebug-Trace-fast-mode t]
4318      ["Continue" edebug-continue-mode t]
4319      ["Continue Fast" edebug-Continue-fast-mode t]
4320      ["Go" edebug-go-mode t]
4321      ["Go Nonstop" edebug-Go-nonstop-mode t]
4322      "----"
4323      ["Help" edebug-help t]
4324      ["Abort" abort-recursive-edit t]
4325      ["Quit to Top Level"  top-level t]
4326      ["Quit Nonstop" edebug-top-level-nonstop t]
4327      "----"
4328     ("Jumps"
4329      ["Forward Sexp" edebug-forward-sexp t]
4330      ["Step In" edebug-step-in t]
4331      ["Step Out" edebug-step-out t]
4332      ["Goto Here" edebug-goto-here t])
4333
4334     ("Breaks"
4335      ["Set Breakpoint" edebug-set-breakpoint t]
4336      ["Unset Breakpoint" edebug-unset-breakpoint t]
4337      ["Set Conditional Breakpoint" edebug-set-conditional-breakpoint t]
4338      ["Set Global Break Condition" edebug-set-global-break-condition t]
4339      ["Show Next Breakpoint" edebug-next-breakpoint t])
4340
4341     ("Views"
4342      ["Where am I?" edebug-where t]
4343      ["Bounce to Current Point" edebug-bounce-point t]
4344      ["View Outside Windows" edebug-view-outside t]
4345      ["Previous Result" edebug-previous-result t]
4346      ["Show Backtrace" edebug-backtrace t]
4347      ["Display Freq Count" edebug-display-freq-count t])
4348
4349     ("Eval"
4350      ["Expression" edebug-eval-expression t]
4351      ["Last Sexp" edebug-eval-last-sexp t]
4352      ["Visit Eval List" edebug-visit-eval-list t])
4353
4354     ("Options"
4355      ["Edebug All Defs" edebug-all-defs
4356       :style toggle :selected edebug-all-defs]
4357      ["Edebug All Forms" edebug-all-forms
4358       :style toggle :selected edebug-all-forms]
4359      "----"
4360      ["Tracing" (edebug-toggle 'edebug-trace)
4361       :style toggle :selected edebug-trace]
4362      ["Test Coverage" (edebug-toggle 'edebug-test-coverage)
4363       :style toggle :selected edebug-test-coverage]
4364      ["Save Windows" edebug-toggle-save-windows
4365       :style toggle :selected edebug-save-windows]
4366      ["Save Point"
4367       (edebug-toggle 'edebug-save-displayed-buffer-points)
4368       :style toggle :selected edebug-save-displayed-buffer-points]
4369      ))
4370   "Menus for Edebug.")
4371
4372 \f
4373 ;;; Emacs version specific code
4374
4375 (defalias 'edebug-window-live-p 'window-live-p)
4376
4377 ;; XEmacs change: We need to bind zmacs-regions to nil around all calls to
4378 ;; `mark' and `mark-marker' but don't bind it to nil before entering a
4379 ;; recursive edit, that is, don't interfere with the binding the user might
4380 ;; see while executing a command.
4381
4382 (defun edebug-mark ()
4383   (let ((zmacs-regions nil))
4384     (mark)))
4385
4386 (defun edebug-set-conditional-breakpoint (arg condition)
4387   "Set a conditional breakpoint at nearest sexp.
4388 The condition is evaluated in the outside context.
4389 With prefix argument, make it a temporary breakpoint."
4390   ;; (interactive "P\nxCondition: ")
4391   (interactive
4392    (list
4393     current-prefix-arg
4394 ;; Read condition as follows; getting previous condition is cumbersome:
4395     (let ((edebug-stop-point (edebug-find-stop-point)))
4396       (if edebug-stop-point
4397           (let* ((edebug-def-name (car edebug-stop-point))
4398                  (index (cdr edebug-stop-point))
4399                  (edebug-data (get edebug-def-name 'edebug))
4400                  (edebug-breakpoints (car (cdr edebug-data)))
4401                  (edebug-break-data (assq index edebug-breakpoints))
4402                  (edebug-break-condition (car (cdr edebug-break-data)))
4403                  (edebug-expression-history
4404                   ;; Prepend the current condition, if any.
4405                   (if edebug-break-condition
4406                       (cons edebug-break-condition read-expression-history)
4407                     read-expression-history)))
4408             (prog1
4409                 (read-from-minibuffer
4410                  "Condition: " nil read-expression-map t
4411                  'edebug-expression-history)
4412               (setq read-expression-history edebug-expression-history)
4413               ))))))
4414   (edebug-modify-breakpoint t condition arg))
4415
4416 ;;; The default for all above is Emacs.
4417
4418 ;; Epoch specific code was in a separate file: edebug-epoch.el.
4419
4420 ;; FSF 21.3:
4421 ;(easy-menu-define edebug-menu edebug-mode-map "Edebug menus" edebug-mode-menus)
4422
4423 ;; XEmacs change
4424 (defun edebug-mode-menu (event)
4425   (interactive "@event")
4426   (popup-menu edebug-mode-menus))
4427
4428 (define-key edebug-mode-map 'button3 'edebug-mode-menu)
4429
4430 \f
4431 ;;; Byte-compiler
4432
4433 ;; Extension for bytecomp to resolve undefined function references.
4434 ;; Requires new byte compiler.
4435
4436 ;; Reenable byte compiler warnings about unread-command-char and -event.
4437 ;; Disabled before edebug-recursive-edit.
4438 (eval-when-compile
4439   (if edebug-unread-command-char-warning
4440       (put 'unread-command-char 'byte-obsolete-variable 
4441            edebug-unread-command-char-warning))
4442   ;; XEmacs addition
4443   (if edebug-unread-command-event-warning
4444       (put 'unread-command-event 'byte-obsolete-variable 
4445            edebug-unread-command-event-warning)))
4446
4447 (eval-when-compile
4448   ;; The body of eval-when-compile seems to get evaluated with eval-defun.
4449   ;; We only want to evaluate when actually byte compiling.
4450   ;; But it is OK to evaluate as long as byte-compiler has been loaded.
4451   (if (featurep 'byte-compile) (progn
4452
4453   (defun byte-compile-resolve-functions (funcs)
4454     "Say it is OK for the named functions to be unresolved."
4455     (mapcar
4456      (function
4457       (lambda (func)
4458         (setq byte-compile-unresolved-functions
4459               (delq (assq func byte-compile-unresolved-functions)
4460                     byte-compile-unresolved-functions))))
4461      funcs)
4462     nil)
4463
4464   '(defun byte-compile-resolve-free-references (vars)
4465      "Say it is OK for the named variables to be referenced."
4466      (mapcar
4467       (function
4468        (lambda (var)
4469          (setq byte-compile-free-references
4470                (delq var byte-compile-free-references))))
4471       vars)
4472      nil)
4473
4474   '(defun byte-compile-resolve-free-assignments (vars)
4475      "Say it is OK for the named variables to be assigned."
4476      (mapcar
4477       (function
4478        (lambda (var)
4479          (setq byte-compile-free-assignments
4480                (delq var byte-compile-free-assignments))))
4481       vars)
4482      nil)
4483
4484   (byte-compile-resolve-functions
4485    '(reporter-submit-bug-report
4486      edebug-gensym ;; also in cl.el
4487      ;; Interfaces to standard functions.
4488      edebug-original-eval-defun
4489      edebug-original-read
4490      edebug-get-buffer-window
4491      edebug-mark
4492      edebug-mark-marker
4493      edebug-input-pending-p
4494      edebug-sit-for
4495      edebug-prin1-to-string
4496      edebug-format
4497      ;; XEmacs
4498      zmacs-deactivate-region
4499      popup-menu
4500      ;; CL
4501      cl-macroexpand-all
4502      ;; And believe it or not, the byte compiler doesn't know about:
4503      byte-compile-resolve-functions
4504      ))
4505
4506   '(byte-compile-resolve-free-references
4507     '(read-expression-history
4508       read-expression-map))
4509
4510   '(byte-compile-resolve-free-assignments
4511     '(read-expression-history))
4512
4513   )))
4514
4515 \f
4516 ;;; Autoloading of Edebug accessories
4517
4518 (if (featurep 'cl)
4519     (add-hook 'edebug-setup-hook
4520               (function (lambda () (require 'cl-specs))))
4521   ;; The following causes cl-specs to be loaded if you load cl.el.
4522   (add-hook 'cl-load-hook
4523             (function (lambda () (require 'cl-specs)))))
4524
4525 ;;; edebug-cl-read and cl-read are available from liberte@cs.uiuc.edu
4526 (if (featurep 'cl-read)
4527     (add-hook 'edebug-setup-hook
4528               (function (lambda () (require 'edebug-cl-read))))
4529   ;; The following causes edebug-cl-read to be loaded when you load cl-read.el.
4530   (add-hook 'cl-read-load-hooks
4531             (function (lambda () (require 'edebug-cl-read)))))
4532
4533 \f
4534 ;;; Finalize Loading
4535
4536 ;;; Finally, hook edebug into the rest of Emacs.
4537 ;;; There are probably some other things that could go here.
4538
4539 ;; Install edebug read and eval functions.
4540 (edebug-install-read-eval-functions)
4541
4542 (provide 'edebug)
4543
4544 ;;; arch-tag: 19c8d05c-4554-426e-ac72-e0fa1fcb0808
4545 ;;; edebug.el ends here