Fix broken hash-table merge.
[bpt/guile.git] / emacs / gds-scheme.el
1 ;;; gds-scheme.el -- GDS function for Scheme mode buffers
2
3 ;;;; Copyright (C) 2005 Neil Jerram
4 ;;;;
5 ;;;; This library is free software; you can redistribute it and/or
6 ;;;; modify it under the terms of the GNU Lesser General Public
7 ;;;; License as published by the Free Software Foundation; either
8 ;;;; version 2.1 of the License, or (at your option) any later
9 ;;;; version.
10 ;;;;
11 ;;;; This library is distributed in the hope that it will be useful,
12 ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
13 ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 ;;;; Lesser General Public License for more details.
15 ;;;;
16 ;;;; You should have received a copy of the GNU Lesser General Public
17 ;;;; License along with this library; if not, write to the Free
18 ;;;; Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
19 ;;;; 02111-1307 USA
20
21 (require 'comint)
22 (require 'scheme)
23 (require 'derived)
24 (require 'pp)
25
26 ;;;; Maintaining an association between a Guile client process and a
27 ;;;; set of Scheme mode buffers.
28
29 (defcustom gds-auto-create-utility-client t
30 "Whether to automatically create a utility Guile client, and
31 associate the current buffer with it, if there are no existing Guile
32 clients available to GDS when the user does something that requires a
33 running Guile client."
34 :type 'boolean
35 :group 'gds)
36
37 (defcustom gds-auto-associate-single-client t
38 "Whether to automatically associate the current buffer with an
39 existing Guile client, if there is only only client known to GDS when
40 the user does something that requires a running Guile client, and the
41 current buffer is not already associated with a Guile client."
42 :type 'boolean
43 :group 'gds)
44
45 (defcustom gds-auto-associate-last-client t
46 "Whether to automatically associate the current buffer with the
47 Guile client that most recently caused that buffer to be displayed,
48 when the user does something that requires a running Guile client and
49 the current buffer is not already associated with a Guile client."
50 :type 'boolean
51 :group 'gds)
52
53 (defvar gds-last-touched-by nil
54 "For each Scheme mode buffer, this records the GDS client that most
55 recently `touched' that buffer in the sense of using it to display
56 source code, for example for the source code relevant to a debugger
57 stack frame.")
58 (make-variable-buffer-local 'gds-last-touched-by)
59
60 (defun gds-auto-associate-buffer ()
61 "Automatically associate the current buffer with a Guile client, if
62 possible."
63 (let* ((num-clients (length gds-client-info))
64 (client
65 (or
66 ;; If there are no clients yet, and
67 ;; `gds-auto-create-utility-client' allows us to create one
68 ;; automatically, do that.
69 (and (= num-clients 0)
70 gds-auto-create-utility-client
71 (gds-start-utility-guile))
72 ;; Otherwise, if there is a single existing client, and
73 ;; `gds-auto-associate-single-client' allows us to use it
74 ;; for automatic association, do that.
75 (and (= num-clients 1)
76 gds-auto-associate-single-client
77 (caar gds-client-info))
78 ;; Otherwise, if the current buffer was displayed because
79 ;; of a Guile client trapping somewhere in its code, and
80 ;; `gds-auto-associate-last-client' allows us to associate
81 ;; with that client, do so.
82 (and gds-auto-associate-last-client
83 gds-last-touched-by))))
84 (if client
85 (gds-associate-buffer client))))
86
87 (defun gds-associate-buffer (client)
88 "Associate the current buffer with the Guile process CLIENT.
89 This means that operations in this buffer that require a running Guile
90 process - such as evaluation, help, completion and setting traps -
91 will be sent to the Guile process whose name or connection number is
92 CLIENT."
93 (interactive (list (gds-choose-client)))
94 ;; If this buffer is already associated, dissociate from its
95 ;; existing client first.
96 (if gds-client (gds-dissociate-buffer))
97 ;; Store the client number in the buffer-local variable gds-client.
98 (setq gds-client client)
99 ;; Add this buffer to the list of buffers associated with the
100 ;; client.
101 (gds-client-put client 'associated-buffers
102 (cons (current-buffer)
103 (gds-client-get client 'associated-buffers))))
104
105 (defun gds-dissociate-buffer ()
106 "Dissociate the current buffer from any specific Guile process."
107 (interactive)
108 (if gds-client
109 (progn
110 ;; Remove this buffer from the list of buffers associated with
111 ;; the current client.
112 (gds-client-put gds-client 'associated-buffers
113 (delq (current-buffer)
114 (gds-client-get gds-client 'associated-buffers)))
115 ;; Reset the buffer-local variable gds-client.
116 (setq gds-client nil)
117 ;; Clear any process status indication from the modeline.
118 (setq mode-line-process nil)
119 (force-mode-line-update))))
120
121 (defun gds-show-client-status (client status-string)
122 "Show a client's status in the modeline of all its associated
123 buffers."
124 (let ((buffers (gds-client-get client 'associated-buffers)))
125 (while buffers
126 (if (buffer-live-p (car buffers))
127 (with-current-buffer (car buffers)
128 (setq mode-line-process status-string)
129 (force-mode-line-update)))
130 (setq buffers (cdr buffers)))))
131
132 (defcustom gds-running-text ":running"
133 "*Mode line text used to show that a Guile process is \"running\".
134 \"Running\" means that the process cannot currently accept any input
135 from the GDS frontend in Emacs, because all of its threads are busy
136 running code that GDS cannot easily interrupt."
137 :type 'string
138 :group 'gds)
139
140 (defcustom gds-ready-text ":ready"
141 "*Mode line text used to show that a Guile process is \"ready\".
142 \"Ready\" means that the process is ready to interact with the GDS
143 frontend in Emacs, because at least one of its threads is waiting for
144 GDS input."
145 :type 'string
146 :group 'gds)
147
148 (defcustom gds-debug-text ":debug"
149 "*Mode line text used to show that a Guile process is \"debugging\".
150 \"Debugging\" means that the process is using the GDS frontend in
151 Emacs to display an error or trap so that the user can debug it."
152 :type 'string
153 :group 'gds)
154
155 (defun gds-choose-client ()
156 "Ask the user to choose a GDS client process from a list."
157 (let ((table '())
158 (default nil))
159 ;; Prepare a table containing all current clients.
160 (mapcar (lambda (client-info)
161 (setq table (cons (cons (cadr (memq 'name client-info))
162 (car client-info))
163 table)))
164 gds-client-info)
165 ;; Add an entry to allow the user to ask for a new process.
166 (setq table (cons (cons "Start a new Guile process" nil) table))
167 ;; Work out a good default. If the buffer has a good value in
168 ;; gds-last-touched-by, we use that; otherwise default to starting
169 ;; a new process.
170 (setq default (or (and gds-last-touched-by
171 (gds-client-get gds-last-touched-by 'name))
172 (caar table)))
173 ;; Read using this table.
174 (let* ((name (completing-read "Choose a Guile process: "
175 table
176 nil
177 t ; REQUIRE-MATCH
178 nil ; INITIAL-INPUT
179 nil ; HIST
180 default))
181 ;; Convert name to a client number.
182 (client (cdr (assoc name table))))
183 ;; If the user asked to start a new Guile process, do that now.
184 (or client (setq client (gds-start-utility-guile)))
185 ;; Return the chosen client ID.
186 client)))
187
188 (defvar gds-last-utility-number 0
189 "Number of the last started Guile utility process.")
190
191 (defun gds-start-utility-guile ()
192 "Start a new utility Guile process."
193 (setq gds-last-utility-number (+ gds-last-utility-number 1))
194 (let* ((procname (format "gds-util[%d]" gds-last-utility-number))
195 (code (format "(begin
196 %s
197 (use-modules (ice-9 gds-client))
198 (run-utility))"
199 (if gds-scheme-directory
200 (concat "(set! %load-path (cons "
201 (format "%S" gds-scheme-directory)
202 " %load-path))")
203 "")))
204 (proc (start-process procname
205 (get-buffer-create procname)
206 gds-guile-program
207 "-q"
208 "--debug"
209 "-c"
210 code))
211 (client nil))
212 ;; Note that this process can be killed automatically on Emacs
213 ;; exit.
214 (process-kill-without-query proc)
215 ;; Set up a process filter to catch the new client's number.
216 (set-process-filter proc
217 (lambda (proc string)
218 (setq client (string-to-number string))
219 (if (process-buffer proc)
220 (with-current-buffer (process-buffer proc)
221 (insert string)))))
222 ;; Accept output from the new process until we have its number.
223 (while (not client)
224 (accept-process-output proc))
225 ;; Return the new process's client number.
226 client))
227
228 ;;;; Evaluating code.
229
230 ;; The following commands send code for evaluation through the GDS TCP
231 ;; connection, receive the result and any output generated through the
232 ;; same connection, and display the result and output to the user.
233 ;;
234 ;; For each buffer where evaluations can be requested, GDS uses the
235 ;; buffer-local variable `gds-client' to track which GDS client
236 ;; program should receive and handle that buffer's evaluations.
237
238 (defun gds-module-name (start end)
239 "Determine and return the name of the module that governs the
240 specified region. The module name is returned as a list of symbols."
241 (interactive "r") ; why not?
242 (save-excursion
243 (goto-char start)
244 (let (module-name)
245 (while (and (not module-name)
246 (beginning-of-defun-raw 1))
247 (if (looking-at "(define-module ")
248 (setq module-name
249 (progn
250 (goto-char (match-end 0))
251 (read (current-buffer))))))
252 module-name)))
253
254 (defcustom gds-emacs-buffer-port-name-prefix "Emacs buffer: "
255 "Prefix used when telling Guile the name of the port from which a
256 chunk of Scheme code (to be evaluated) comes. GDS uses this prefix,
257 followed by the buffer name, in two cases: when the buffer concerned
258 is not associated with a file, or if the buffer has been modified
259 since last saving to its file. In the case where the buffer is
260 identical to a saved file, GDS uses the file name as the port name."
261 :type '(string)
262 :group 'gds)
263
264 (defun gds-port-name (start end)
265 "Return port name for the specified region of the current buffer.
266 The name will be used by Guile as the port name when evaluating that
267 region's code."
268 (or (and (not (buffer-modified-p))
269 buffer-file-name)
270 (concat gds-emacs-buffer-port-name-prefix (buffer-name))))
271
272 (defun gds-line-and-column (pos)
273 "Return 0-based line and column number at POS."
274 (let (line column)
275 (save-excursion
276 (goto-char pos)
277 (setq column (current-column))
278 (beginning-of-line)
279 (setq line (count-lines (point-min) (point))))
280 (cons line column)))
281
282 (defun gds-eval-region (start end &optional debugp)
283 "Evaluate the current region. If invoked with `C-u' prefix (or, in
284 a program, with optional DEBUGP arg non-nil), pause and pop up the
285 stack at the start of the evaluation, so that the user can single-step
286 through the code."
287 (interactive "r\nP")
288 (or gds-client
289 (gds-auto-associate-buffer)
290 (call-interactively 'gds-associate-buffer))
291 (let ((module (gds-module-name start end))
292 (port-name (gds-port-name start end))
293 (lc (gds-line-and-column start)))
294 (let ((code (buffer-substring-no-properties start end)))
295 (gds-send (format "eval (region . %S) %s %S %d %d %S %s"
296 (gds-abbreviated code)
297 (if module (prin1-to-string module) "#f")
298 port-name (car lc) (cdr lc)
299 code
300 (if debugp '(debug) '(none)))
301 gds-client))))
302
303 (defun gds-eval-expression (expr &optional correlator debugp)
304 "Evaluate the supplied EXPR (a string). If invoked with `C-u'
305 prefix (or, in a program, with optional DEBUGP arg non-nil), pause and
306 pop up the stack at the start of the evaluation, so that the user can
307 single-step through the code."
308 (interactive "sEvaluate expression: \ni\nP")
309 (or gds-client
310 (gds-auto-associate-buffer)
311 (call-interactively 'gds-associate-buffer))
312 (set-text-properties 0 (length expr) nil expr)
313 (gds-send (format "eval (%S . %S) #f \"Emacs expression\" 0 0 %S %s"
314 (or correlator 'expression)
315 (gds-abbreviated expr)
316 expr
317 (if debugp '(debug) '(none)))
318 gds-client))
319
320 (defconst gds-abbreviated-length 35)
321
322 (defun gds-abbreviated (code)
323 (let ((nlpos (string-match (regexp-quote "\n") code)))
324 (while nlpos
325 (setq code
326 (if (= nlpos (- (length code) 1))
327 (substring code 0 nlpos)
328 (concat (substring code 0 nlpos)
329 "\\n"
330 (substring code (+ nlpos 1)))))
331 (setq nlpos (string-match (regexp-quote "\n") code))))
332 (if (> (length code) gds-abbreviated-length)
333 (concat (substring code 0 (- gds-abbreviated-length 3)) "...")
334 code))
335
336 (defun gds-eval-defun (&optional debugp)
337 "Evaluate the defun (top-level form) at point. If invoked with
338 `C-u' prefix (or, in a program, with optional DEBUGP arg non-nil),
339 pause and pop up the stack at the start of the evaluation, so that the
340 user can single-step through the code."
341 (interactive "P")
342 (save-excursion
343 (end-of-defun)
344 (let ((end (point)))
345 (beginning-of-defun)
346 (gds-eval-region (point) end debugp))))
347
348 (defun gds-eval-last-sexp (&optional debugp)
349 "Evaluate the sexp before point. If invoked with `C-u' prefix (or,
350 in a program, with optional DEBUGP arg non-nil), pause and pop up the
351 stack at the start of the evaluation, so that the user can single-step
352 through the code."
353 (interactive "P")
354 (gds-eval-region (save-excursion (backward-sexp) (point)) (point) debugp))
355
356 ;;;; Help.
357
358 ;; Help is implemented as a special case of evaluation, identified by
359 ;; the evaluation correlator 'help.
360
361 (defun gds-help-symbol (sym)
362 "Get help for SYM (a Scheme symbol)."
363 (interactive
364 (let ((sym (thing-at-point 'symbol))
365 (enable-recursive-minibuffers t)
366 val)
367 (setq val (read-from-minibuffer
368 (if sym
369 (format "Describe Guile symbol (default %s): " sym)
370 "Describe Guile symbol: ")))
371 (list (if (zerop (length val)) sym val))))
372 (gds-eval-expression (format "(help %s)" sym) 'help))
373
374 (defun gds-apropos (regex)
375 "List Guile symbols matching REGEX."
376 (interactive
377 (let ((sym (thing-at-point 'symbol))
378 (enable-recursive-minibuffers t)
379 val)
380 (setq val (read-from-minibuffer
381 (if sym
382 (format "Guile apropos (regexp, default \"%s\"): " sym)
383 "Guile apropos (regexp): ")))
384 (list (if (zerop (length val)) sym val))))
385 (set-text-properties 0 (length regex) nil regex)
386 (gds-eval-expression (format "(apropos %S)" regex) 'apropos))
387
388 ;;;; Displaying results of help and eval.
389
390 (defun gds-display-results (client correlator stack-available results)
391 (let* ((helpp+bufname (cond ((eq (car correlator) 'help)
392 '(t . "*Guile Help*"))
393 ((eq (car correlator) 'apropos)
394 '(t . "*Guile Apropos*"))
395 (t
396 '(nil . "*Guile Evaluation*"))))
397 (helpp (car helpp+bufname)))
398 (let ((buf (get-buffer-create (cdr helpp+bufname))))
399 (save-selected-window
400 (save-excursion
401 (set-buffer buf)
402 (gds-dissociate-buffer)
403 (erase-buffer)
404 (scheme-mode)
405 (insert (cdr correlator) "\n\n")
406 (while results
407 (insert (car results))
408 (or (bolp) (insert "\\\n"))
409 (if helpp
410 nil
411 (if (cadr results)
412 (mapcar (function (lambda (value)
413 (insert " => " value "\n")))
414 (cadr results))
415 (insert " => no (or unspecified) value\n"))
416 (insert "\n"))
417 (setq results (cddr results)))
418 (if stack-available
419 (let ((beg (point))
420 (map (make-sparse-keymap)))
421 (define-key map [mouse-1] 'gds-show-last-stack)
422 (define-key map "\C-m" 'gds-show-last-stack)
423 (insert "[click here to show error stack]")
424 (add-text-properties beg (point)
425 (list 'keymap map
426 'mouse-face 'highlight))
427 (insert "\n")))
428 (goto-char (point-min))
429 (gds-associate-buffer client))
430 (pop-to-buffer buf)
431 (run-hooks 'temp-buffer-show-hook)))))
432
433 (defun gds-show-last-stack ()
434 "Show stack of the most recent error."
435 (interactive)
436 (or gds-client
437 (gds-auto-associate-buffer)
438 (call-interactively 'gds-associate-buffer))
439 (gds-send "debug-lazy-trap-context" gds-client))
440
441 ;;;; Completion.
442
443 (defvar gds-completion-results nil)
444
445 (defun gds-complete-symbol ()
446 "Complete the Guile symbol before point. Returns `t' if anything
447 interesting happened, `nil' if not."
448 (interactive)
449 (or gds-client
450 (gds-auto-associate-buffer)
451 (call-interactively 'gds-associate-buffer))
452 (let* ((chars (- (point) (save-excursion
453 (while (let ((syntax (char-syntax (char-before (point)))))
454 (or (eq syntax ?w) (eq syntax ?_)))
455 (forward-char -1))
456 (point)))))
457 (if (zerop chars)
458 nil
459 (setq gds-completion-results nil)
460 (gds-send (format "complete %s"
461 (prin1-to-string
462 (buffer-substring-no-properties (- (point) chars)
463 (point))))
464 gds-client)
465 (while (null gds-completion-results)
466 (accept-process-output gds-debug-server 0 200))
467 (cond ((eq gds-completion-results 'error)
468 (error "Internal error - please report the contents of the *Guile Evaluation* window"))
469 ((eq gds-completion-results t)
470 nil)
471 ((stringp gds-completion-results)
472 (if (<= (length gds-completion-results) chars)
473 nil
474 (insert (substring gds-completion-results chars))
475 (message "Sole completion")
476 t))
477 ((= (length gds-completion-results) 1)
478 (if (<= (length (car gds-completion-results)) chars)
479 nil
480 (insert (substring (car gds-completion-results) chars))
481 t))
482 (t
483 (with-output-to-temp-buffer "*Completions*"
484 (display-completion-list gds-completion-results))
485 t)))))
486
487 ;;;; Breakpoints.
488
489 (defvar gds-bufferless-breakpoints nil
490 "The list of breakpoints that are not yet associated with a
491 particular buffer. Each element looks like (BPDEF BPNUM) where BPDEF
492 is the breakpoint definition and BPNUM the breakpoint's unique
493 GDS-assigned number. A breakpoint definition BPDEF is a list of the
494 form (BEHAVIOUR TYPE FILENAME TYPE-ARGS...), where BEHAVIOUR is 'debug
495 or 'trace, TYPE is 'in or 'at, FILENAME is the full name of the file
496 where the breakpoint is (or will be) set, and TYPE-ARGS is:
497
498 - the name of the procedure to break in, if TYPE is 'in
499
500 - the line number and column number to break at, if TYPE is 'at.
501
502 If persistent breakpoints are enabled (by configuring
503 gds-breakpoints-file-name), this list is initialized when GDS is
504 loaded by reading gds-breakpoints-file-name.")
505
506 (defsubst gds-bpdef:behaviour (bpdef)
507 (nth 0 bpdef))
508
509 (defsubst gds-bpdef:type (bpdef)
510 (nth 1 bpdef))
511
512 (defsubst gds-bpdef:file-name (bpdef)
513 (nth 2 bpdef))
514
515 (defsubst gds-bpdef:proc-name (bpdef)
516 (nth 3 bpdef))
517
518 (defsubst gds-bpdef:lc (bpdef)
519 (nth 3 bpdef))
520
521 (defvar gds-breakpoint-number 0
522 "The last assigned breakpoint number. GDS increments this whenever
523 it creates a new breakpoint.")
524
525 (defvar gds-breakpoint-buffers nil
526 "The list of buffers that contain GDS breakpoints. When Emacs
527 visits a Scheme file, GDS checks to see if any of the breakpoints in
528 the bufferless list can be assigned to that file's buffer. If they
529 can, they are removed from the bufferless list and become breakpoint
530 overlays in that buffer. To retain the ability to enumerate all
531 breakpoints, therefore, we keep a list of all such buffers.")
532
533 (defvar gds-breakpoint-programming nil
534 "Information about how each breakpoint is actually programmed in the
535 Guile clients that GDS is connected to. This is an alist of the form
536 \((BPNUM (CLIENT . TRAPLIST) ...) ...), where BPNUM is the breakpoint
537 number, CLIENT is the number of a GDS client, and TRAPLIST is the list
538 of traps that that client has created for the breakpoint concerned (in
539 an arbitrary but Emacs-readable format).")
540
541 (defvar gds-breakpoint-cache nil
542 "Buffer-local cache of breakpoints in a particular buffer. When a
543 breakpoint is represented as an overlay is a Scheme mode buffer, we
544 need to be able to detect when the user has caused that overlay to
545 evaporate by deleting a region of code that included it. We do this
546 detection when the buffer is next saved, by comparing the current set
547 of overlays with this cache. The cache is a list in which each
548 element has the form (BPDEF BPNUM), with BPDEF and BPNUM as already
549 described. The handling of such breakpoints (which we call \"lost\")
550 is controlled by the setting of gds-delete-lost-breakpoints.")
551 (make-variable-buffer-local 'gds-breakpoint-cache)
552
553 (defface gds-breakpoint-face
554 '((((background dark)) (:background "red"))
555 (t (:background "pink")))
556 "*Face used to highlight the location of a breakpoint."
557 :group 'gds)
558
559 (defcustom gds-breakpoints-file-name "~/.gds-breakpoints"
560 "Name of file used to store GDS breakpoints between sessions.
561 You can disable breakpoint persistence by setting this to nil."
562 :group 'gds
563 :type '(choice (const :tag "nil" nil) file))
564
565 (defcustom gds-delete-lost-breakpoints nil
566 "Whether to delete lost breakpoints.
567
568 A non-nil value means that the Guile clients where lost breakpoints
569 were programmed will be told immediately to delete their breakpoints.
570 \"Immediately\" means when the lost breakpoints are detected, which
571 means when the buffer that previously contained them is saved. Thus,
572 even if the affected code (which the GDS user has deleted from his/her
573 buffer in Emacs) is still in use in the Guile clients, the breakpoints
574 that were previously set in that code will no longer take effect.
575
576 Nil (which is the default) means that GDS leaves such breakpoints
577 active in their Guile clients. This allows those breakpoints to
578 continue taking effect until the affected code is no longer used by
579 the Guile clients."
580 :group 'gds
581 :type 'boolean)
582
583 (defvar gds-bpdefs-cache nil)
584
585 (defun gds-read-breakpoints-file ()
586 "Read the persistent breakpoints file, and use its contents to
587 initialize GDS's global breakpoint variables."
588 (let ((bpdefs (condition-case nil
589 (with-current-buffer
590 (find-file-noselect gds-breakpoints-file-name)
591 (goto-char (point-min))
592 (read (current-buffer)))
593 (error nil))))
594 ;; Cache the overall value so we don't unnecessarily modify the
595 ;; breakpoints buffer when `gds-write-breakpoints-file' is called.
596 (setq gds-bpdefs-cache bpdefs)
597 ;; Move definitions into the bufferless breakpoint list, assigning
598 ;; breakpoint numbers as we go.
599 (setq gds-bufferless-breakpoints
600 (mapcar (function (lambda (bpdef)
601 (setq gds-breakpoint-number
602 (1+ gds-breakpoint-number))
603 (list bpdef gds-breakpoint-number)))
604 bpdefs))
605 ;; Check each existing Scheme buffer to see if it wants to take
606 ;; ownership of any of these breakpoints.
607 (mapcar (function (lambda (buffer)
608 (with-current-buffer buffer
609 (if (eq (derived-mode-class major-mode) 'scheme-mode)
610 (gds-adopt-breakpoints)))))
611 (buffer-list))))
612
613 (defun gds-adopt-breakpoints ()
614 "Take ownership of any of the breakpoints in the bufferless list
615 that match the current buffer."
616 (mapcar (function gds-adopt-breakpoint)
617 (copy-sequence gds-bufferless-breakpoints)))
618
619 (defun gds-adopt-breakpoint (bpdefnum)
620 "Take ownership of the specified breakpoint if it matches the
621 current buffer."
622 (let ((bpdef (car bpdefnum))
623 (bpnum (cadr bpdefnum)))
624 ;; Check if breakpoint's file name matches. If it does, try to
625 ;; convert the breakpoint definition to a breakpoint overlay in
626 ;; the current buffer.
627 (if (and (string-equal (gds-bpdef:file-name bpdef) buffer-file-name)
628 (gds-make-breakpoint-overlay bpdef bpnum))
629 ;; That all succeeded, so this breakpoint is no longer
630 ;; bufferless.
631 (setq gds-bufferless-breakpoints
632 (delq bpdefnum gds-bufferless-breakpoints)))))
633
634 (defun gds-make-breakpoint-overlay (bpdef &optional bpnum)
635 ;; If no explicit number given, assign the next available breakpoint
636 ;; number.
637 (or bpnum
638 (setq gds-breakpoint-number (+ gds-breakpoint-number 1)
639 bpnum gds-breakpoint-number))
640 ;; First decide where the overlay should be, and create it there.
641 (let ((o (cond ((eq (gds-bpdef:type bpdef) 'at)
642 (save-excursion
643 (goto-line (+ (car (gds-bpdef:lc bpdef)) 1))
644 (move-to-column (cdr (gds-bpdef:lc bpdef)))
645 (make-overlay (point) (1+ (point)))))
646 ((eq (gds-bpdef:type bpdef) 'in)
647 (save-excursion
648 (goto-char (point-min))
649 (and (re-search-forward (concat "^(define +(?\\("
650 (regexp-quote
651 (gds-bpdef:proc-name
652 bpdef))
653 "\\>\\)")
654 nil t)
655 (make-overlay (match-beginning 1) (match-end 1)))))
656 (t
657 (error "Bad breakpoint type")))))
658 ;; If that succeeded, initialize the overlay's properties.
659 (if o
660 (progn
661 (overlay-put o 'evaporate t)
662 (overlay-put o 'face 'gds-breakpoint-face)
663 (overlay-put o 'gds-breakpoint-number bpnum)
664 (overlay-put o 'gds-breakpoint-definition bpdef)
665 (overlay-put o 'help-echo (format "Breakpoint %d: %S" bpnum bpdef))
666 (overlay-put o 'priority 1000)
667 ;; Make sure that the current buffer is included in
668 ;; `gds-breakpoint-buffers'.
669 (or (memq (current-buffer) gds-breakpoint-buffers)
670 (setq gds-breakpoint-buffers
671 (cons (current-buffer) gds-breakpoint-buffers)))
672 ;; Add the new breakpoint to this buffer's cache.
673 (setq gds-breakpoint-cache
674 (cons (list bpdef bpnum) gds-breakpoint-cache))
675 ;; If this buffer is associated with a client, tell the
676 ;; client about the new breakpoint.
677 (if gds-client (gds-send-breakpoint-to-client bpnum bpdef))))
678 ;; Return the overlay, or nil if we weren't able to convert the
679 ;; breakpoint definition.
680 o))
681
682 (defun gds-send-breakpoint-to-client (bpnum bpdef)
683 "Send specified breakpoint to this buffer's Guile client."
684 (gds-send (format "set-breakpoint %d %S" bpnum bpdef) gds-client))
685
686 (add-hook 'scheme-mode-hook (function gds-adopt-breakpoints))
687
688 (defcustom gds-default-breakpoint-type 'debug
689 "The type of breakpoint set by `C-x SPC'."
690 :group 'gds
691 :type '(choice (const :tag "debug" debug) (const :tag "trace" trace)))
692
693 (defun gds-set-breakpoint ()
694 "Create a new GDS breakpoint at point."
695 (interactive)
696 ;; Set up beg and end according to whether the mark is active.
697 (if mark-active
698 ;; Set new breakpoints on all opening parentheses in the region.
699 (let ((beg (region-beginning))
700 (end (region-end)))
701 (save-excursion
702 (goto-char beg)
703 (beginning-of-defun)
704 (let ((defun-start (point)))
705 (goto-char beg)
706 (while (search-forward "(" end t)
707 (let ((state (parse-partial-sexp defun-start (point)))
708 (pos (- (point) 1)))
709 (or (nth 3 state)
710 (nth 4 state)
711 (gds-breakpoint-overlays-at pos)
712 (gds-make-breakpoint-overlay (list gds-default-breakpoint-type
713 'at
714 buffer-file-name
715 (gds-line-and-column
716 pos)))))))))
717 ;; Set a new breakpoint on the defun at point.
718 (let ((region (gds-defun-name-region)))
719 ;; Complain if there is no defun at point.
720 (or region
721 (error "Point is not in a procedure definition"))
722 ;; Don't create another breakpoint if there is already one here.
723 (if (gds-breakpoint-overlays-at (car region))
724 (error "There is already a breakpoint here"))
725 ;; Create and return the new breakpoint overlay.
726 (gds-make-breakpoint-overlay (list gds-default-breakpoint-type
727 'in
728 buffer-file-name
729 (buffer-substring-no-properties
730 (car region)
731 (cdr region))))))
732 ;; Update the persistent breakpoints file.
733 (gds-write-breakpoints-file))
734
735 (defun gds-defun-name-region ()
736 "If point is in a defun, return the beginning and end positions of
737 the identifier being defined."
738 (save-excursion
739 (let ((p (point)))
740 (beginning-of-defun)
741 ;; Check that we are looking at some kind of procedure
742 ;; definition.
743 (and (looking-at "(define +(?\\(\\(\\s_\\|\\w\\)+\\)")
744 (let ((beg (match-beginning 1))
745 (end (match-end 1)))
746 (end-of-defun)
747 ;; Check here that we have reached past the original point
748 ;; position.
749 (and (>= (point) p)
750 (cons beg end)))))))
751
752 (defun gds-breakpoint-overlays-at (pos)
753 "Return a list of GDS breakpoint overlays at the specified position."
754 (let ((os (overlays-at pos))
755 (breakpoint-os nil))
756 ;; Of the overlays at POS, select all those that have a
757 ;; gds-breakpoint-definition property.
758 (while os
759 (if (overlay-get (car os) 'gds-breakpoint-definition)
760 (setq breakpoint-os (cons (car os) breakpoint-os)))
761 (setq os (cdr os)))
762 breakpoint-os))
763
764 (defun gds-write-breakpoints-file ()
765 "Write the persistent breakpoints file, if configured."
766 (if gds-breakpoints-file-name
767 (let ((bpdefs (gds-fold-breakpoints (function (lambda (bpnum bpdef init)
768 (cons bpdef init)))
769 t)))
770 (or (equal bpdefs gds-bpdefs-cache)
771 (with-current-buffer (find-file-noselect gds-breakpoints-file-name)
772 (erase-buffer)
773 (pp (reverse bpdefs) (current-buffer))
774 (setq gds-bpdefs-cache bpdefs)
775 (let ((auto-fill-function normal-auto-fill-function))
776 (newline)))))))
777
778 (defun gds-fold-breakpoints (fn &optional foldp init)
779 ;; Run through bufferless breakpoints first.
780 (let ((bbs gds-bufferless-breakpoints))
781 (while bbs
782 (let ((bpnum (cadr (car bbs)))
783 (bpdef (caar bbs)))
784 (if foldp
785 (setq init (funcall fn bpnum bpdef init))
786 (funcall fn bpnum bpdef)))
787 (setq bbs (cdr bbs))))
788 ;; Now run through breakpoint buffers.
789 (let ((outbuf (current-buffer))
790 (bpbufs gds-breakpoint-buffers))
791 (while bpbufs
792 (let ((buf (car bpbufs)))
793 (if (buffer-live-p buf)
794 (with-current-buffer buf
795 (save-restriction
796 (widen)
797 (let ((os (overlays-in (point-min) (point-max))))
798 (while os
799 (let ((bpnum (overlay-get (car os)
800 'gds-breakpoint-number))
801 (bpdef (overlay-get (car os)
802 'gds-breakpoint-definition)))
803 (if bpdef
804 (with-current-buffer outbuf
805 (if foldp
806 (setq init (funcall fn bpnum bpdef init))
807 (funcall fn bpnum bpdef)))))
808 (setq os (cdr os))))))))
809 (setq bpbufs (cdr bpbufs))))
810 init)
811
812 (defun gds-delete-breakpoints ()
813 "Delete GDS breakpoints in the region or at point."
814 (interactive)
815 (if mark-active
816 ;; Delete all breakpoints in the region.
817 (let ((os (overlays-in (region-beginning) (region-end))))
818 (while os
819 (if (overlay-get (car os) 'gds-breakpoint-definition)
820 (gds-delete-breakpoint (car os)))
821 (setq os (cdr os))))
822 ;; Delete the breakpoint "at point".
823 (call-interactively (function gds-delete-breakpoint))))
824
825 (defun gds-delete-breakpoint (o)
826 (interactive (list (or (gds-breakpoint-at-point)
827 (error "There is no breakpoint here"))))
828 (let ((bpdef (overlay-get o 'gds-breakpoint-definition))
829 (bpnum (overlay-get o 'gds-breakpoint-number)))
830 ;; If this buffer is associated with a client, tell the client
831 ;; that the breakpoint has been deleted.
832 (if (and bpnum gds-client)
833 (gds-send (format "delete-breakpoint %d" bpnum) gds-client))
834 ;; Remove this breakpoint from the cache also, so it isn't later
835 ;; detected as having been "lost".
836 (setq gds-breakpoint-cache
837 (delq (assq bpdef gds-breakpoint-cache) gds-breakpoint-cache)))
838 ;; Remove the overlay from its buffer.
839 (delete-overlay o)
840 ;; If that was the last breakpoint in this buffer, remove this
841 ;; buffer from gds-breakpoint-buffers.
842 (or gds-breakpoint-cache
843 (setq gds-breakpoint-buffers
844 (delq (current-buffer) gds-breakpoint-buffers)))
845 ;; Update the persistent breakpoints file.
846 (gds-write-breakpoints-file))
847
848 (defun gds-breakpoint-at-point ()
849 "Find and return the overlay for a breakpoint `at' the current
850 cursor position. This is intended for use in other functions'
851 interactive forms, so it intentionally uses the minibuffer in some
852 situations."
853 (let* ((region (gds-defun-name-region))
854 (os (gds-union (gds-breakpoint-overlays-at (point))
855 (and region
856 (gds-breakpoint-overlays-at (car region))))))
857 ;; Switch depending whether we found 0, 1 or more overlays.
858 (cond ((null os)
859 ;; None found: return nil.
860 nil)
861 ((= (length os) 1)
862 ;; One found: return it.
863 (car os))
864 (t
865 ;; More than 1 found: ask the user to choose.
866 (gds-user-selected-breakpoint os)))))
867
868 (defun gds-union (first second &rest others)
869 (if others
870 (gds-union first (apply 'gds-union second others))
871 (progn
872 (while first
873 (or (memq (car first) second)
874 (setq second (cons (car first) second)))
875 (setq first (cdr first)))
876 second)))
877
878 (defun gds-user-selected-breakpoint (os)
879 "Ask the user to choose one of the given list of breakpoints, and
880 return the one that they chose."
881 (let ((table (mapcar
882 (lambda (o)
883 (cons (format "%S"
884 (overlay-get o 'gds-breakpoint-definition))
885 o))
886 os)))
887 (cdr (assoc (completing-read "Which breakpoint do you mean? "
888 table nil t)
889 table))))
890
891 (defun gds-describe-breakpoints ()
892 "Describe all breakpoints and their programming status."
893 (interactive)
894 (with-current-buffer (get-buffer-create "*GDS Breakpoints*")
895 (erase-buffer)
896 (gds-fold-breakpoints (function gds-describe-breakpoint))
897 (display-buffer (current-buffer))))
898
899 (defun gds-describe-breakpoint (bpnum bpdef)
900 (insert (format "Breakpoint %d: %S\n" bpnum bpdef))
901 (let ((bpproglist (cdr (assq bpnum gds-breakpoint-programming))))
902 (mapcar (lambda (clientprog)
903 (let ((client (car clientprog))
904 (traplist (cdr clientprog)))
905 (mapcar (lambda (trap)
906 (insert (format " Client %d: %S\n" client trap)))
907 traplist)))
908 bpproglist)))
909
910 (defun gds-after-save-update-breakpoints ()
911 "Function called when a buffer containing breakpoints is saved."
912 (if (eq (derived-mode-class major-mode) 'scheme-mode)
913 (save-restriction
914 (widen)
915 ;; Get the current breakpoint overlays.
916 (let ((os (overlays-in (point-min) (point-max)))
917 (cache (copy-sequence gds-breakpoint-cache)))
918 ;; Identify any overlays that have disappeared by comparing
919 ;; against this buffer's definition cache, and
920 ;; simultaneously rebuild the cache to reflect the current
921 ;; set of overlays.
922 (setq gds-breakpoint-cache nil)
923 (while os
924 (let* ((o (car os))
925 (bpdef (overlay-get o 'gds-breakpoint-definition))
926 (bpnum (overlay-get o 'gds-breakpoint-number)))
927 (if bpdef
928 ;; o and bpdef describe a current breakpoint.
929 (progn
930 ;; Remove this breakpoint from the old cache list,
931 ;; so we don't think it got lost.
932 (setq cache (delq (assq bpdef cache) cache))
933 ;; Check whether this breakpoint's location has
934 ;; moved. If it has, update the breakpoint
935 ;; definition and the associated client.
936 (let ((lcnow (gds-line-and-column (overlay-start o))))
937 (if (equal lcnow (gds-bpdef:lc bpdef))
938 nil ; Breakpoint hasn't moved.
939 (gds-bpdef:setlc bpdef lcnow)
940 (if gds-client
941 (gds-send-breakpoint-to-client bpnum bpdef))))
942 ;; Add this breakpoint to the new cache list.
943 (setq gds-breakpoint-cache
944 (cons (list bpdef bpnum) gds-breakpoint-cache)))))
945 (setq os (cdr os)))
946 ;; cache now holds the set of lost breakpoints. If we are
947 ;; supposed to explicitly delete these from the associated
948 ;; client, do that now.
949 (if (and gds-delete-lost-breakpoints gds-client)
950 (while cache
951 (gds-send (format "delete-breakpoint %d" (cadr (car cache)))
952 gds-client)
953 (setq cache (cdr cache)))))
954 ;; If this buffer now has no breakpoints, remove it from
955 ;; gds-breakpoint-buffers.
956 (or gds-breakpoint-cache
957 (setq gds-breakpoint-buffers
958 (delq (current-buffer) gds-breakpoint-buffers)))
959 ;; Update the persistent breakpoints file.
960 (gds-write-breakpoints-file))))
961
962 (add-hook 'after-save-hook (function gds-after-save-update-breakpoints))
963
964 ;;;; Dispatcher for non-debug protocol.
965
966 (defun gds-nondebug-protocol (client proc args)
967 (cond (;; (eval-results ...) - Results of evaluation.
968 (eq proc 'eval-results)
969 (gds-display-results client (car args) (cadr args) (cddr args))
970 ;; If these results indicate an error, set
971 ;; gds-completion-results to non-nil in case the error arose
972 ;; when trying to do a completion.
973 (if (eq (caar args) 'error)
974 (setq gds-completion-results 'error)))
975
976 (;; (completion-result ...) - Available completions.
977 (eq proc 'completion-result)
978 (setq gds-completion-results (or (car args) t)))
979
980 (;; (breakpoint NUM STATUS) - Breakpoint set.
981 (eq proc 'breakpoint)
982 (let* ((bpnum (car args))
983 (traplist (cdr args))
984 (bpentry (assq bpnum gds-breakpoint-programming)))
985 (message "Breakpoint %d: %s" bpnum traplist)
986 (if bpentry
987 (let ((cliententry (assq client (cdr bpentry))))
988 (if cliententry
989 (setcdr cliententry traplist)
990 (setcdr bpentry
991 (cons (cons client traplist) (cdr bpentry)))))
992 (setq gds-breakpoint-programming
993 (cons (list bpnum (cons client traplist))
994 gds-breakpoint-programming)))))
995
996 (;; (get-breakpoints) - Set all breakpoints.
997 (eq proc 'get-breakpoints)
998 (let ((gds-client client))
999 (gds-fold-breakpoints (function gds-send-breakpoint-to-client)))
1000 (gds-send "continue" client))
1001
1002 (;; (note ...) - For debugging only.
1003 (eq proc 'note))
1004
1005 (;; (trace ...) - Tracing.
1006 (eq proc 'trace)
1007 (with-current-buffer (get-buffer-create "*GDS Trace*")
1008 (save-excursion
1009 (goto-char (point-max))
1010 (or (bolp) (insert "\n"))
1011 (insert "[client " (number-to-string client) "] " (car args) "\n"))))
1012
1013 (t
1014 ;; Unexpected.
1015 (error "Bad protocol: %S" form))))
1016
1017 ;;;; Scheme mode keymap items.
1018
1019 (define-key scheme-mode-map "\M-\C-x" 'gds-eval-defun)
1020 (define-key scheme-mode-map "\C-x\C-e" 'gds-eval-last-sexp)
1021 (define-key scheme-mode-map "\C-c\C-e" 'gds-eval-expression)
1022 (define-key scheme-mode-map "\C-c\C-r" 'gds-eval-region)
1023 (define-key scheme-mode-map "\C-hg" 'gds-help-symbol)
1024 (define-key scheme-mode-map "\C-h\C-g" 'gds-apropos)
1025 (define-key scheme-mode-map "\C-hG" 'gds-apropos)
1026 (define-key scheme-mode-map "\C-hS" 'gds-show-last-stack)
1027 (define-key scheme-mode-map "\e\t" 'gds-complete-symbol)
1028 (define-key scheme-mode-map "\C-x " 'gds-set-breakpoint)
1029
1030 (define-prefix-command 'gds-breakpoint-map)
1031 (define-key scheme-mode-map "\C-c\C-b" 'gds-breakpoint-map)
1032 (define-key gds-breakpoint-map " " 'gds-set-breakpoint)
1033 (define-key gds-breakpoint-map "d"
1034 (function (lambda ()
1035 (interactive)
1036 (let ((gds-default-breakpoint-type 'debug))
1037 (gds-set-breakpoint)))))
1038 (define-key gds-breakpoint-map "t"
1039 (function (lambda ()
1040 (interactive)
1041 (let ((gds-default-breakpoint-type 'trace))
1042 (gds-set-breakpoint)))))
1043 (define-key gds-breakpoint-map "T"
1044 (function (lambda ()
1045 (interactive)
1046 (let ((gds-default-breakpoint-type 'trace-subtree))
1047 (gds-set-breakpoint)))))
1048 (define-key gds-breakpoint-map [backspace] 'gds-delete-breakpoints)
1049 (define-key gds-breakpoint-map "?" 'gds-describe-breakpoints)
1050
1051 ;;;; The end!
1052
1053 (provide 'gds-scheme)
1054
1055 ;;; gds-scheme.el ends here.