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