1;;; gud.el --- Grand Unified Debugger mode for running GDB and other debuggers
2
3;; Author: Eric S. Raymond <esr@snark.thyrsus.com>
4;; Maintainer: FSF
5;; Keywords: unix, tools
6
7;; Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 2000, 2001, 2002, 2003,
8;;  2004, 2005, 2006, 2007 Free Software Foundation, Inc.
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;; The ancestral gdb.el was by W. Schelter <wfs@rascal.ics.utexas.edu> It was
30;; later rewritten by rms.  Some ideas were due to Masanobu.  Grand
31;; Unification (sdb/dbx support) by Eric S. Raymond <esr@thyrsus.com> Barry
32;; Warsaw <bwarsaw@cen.com> hacked the mode to use comint.el.  Shane Hartman
33;; <shane@spr.com> added support for xdb (HPUX debugger).  Rick Sladkey
34;; <jrs@world.std.com> wrote the GDB command completion code.  Dave Love
35;; <d.love@dl.ac.uk> added the IRIX kluge, re-implemented the Mips-ish variant
36;; and added a menu. Brian D. Carlstrom <bdc@ai.mit.edu> combined the IRIX
37;; kluge with the gud-xdb-directories hack producing gud-dbx-directories.
38;; Derek L. Davies <ddavies@world.std.com> added support for jdb (Java
39;; debugger.)
40
41;;; Code:
42
43(eval-when-compile (require 'cl)) ; for case macro
44
45(require 'comint)
46
47(defvar gdb-active-process)
48(defvar gdb-define-alist)
49(defvar gdb-macro-info)
50(defvar gdb-server-prefix)
51(defvar gdb-show-changed-values)
52(defvar gdb-var-list)
53(defvar gdb-speedbar-auto-raise)
54(defvar tool-bar-map)
55
56;; ======================================================================
57;; GUD commands must be visible in C buffers visited by GUD
58
59(defgroup gud nil
60  "Grand Unified Debugger mode for gdb and other debuggers under Emacs.
61Supported debuggers include gdb, sdb, dbx, xdb, perldb, pdb (Python), jdb."
62  :group 'unix
63  :group 'tools)
64
65
66(defcustom gud-key-prefix "\C-x\C-a"
67  "Prefix of all GUD commands valid in C buffers."
68  :type 'string
69  :group 'gud)
70
71(global-set-key (concat gud-key-prefix "\C-l") 'gud-refresh)
72(define-key ctl-x-map " " 'gud-break)	;; backward compatibility hack
73
74(defvar gud-marker-filter nil)
75(put 'gud-marker-filter 'permanent-local t)
76(defvar gud-find-file nil)
77(put 'gud-find-file 'permanent-local t)
78
79(defun gud-marker-filter (&rest args)
80  (apply gud-marker-filter args))
81
82(defvar gud-minor-mode nil)
83(put 'gud-minor-mode 'permanent-local t)
84
85(defvar gud-comint-buffer nil)
86
87(defvar gud-keep-buffer nil)
88
89(defun gud-symbol (sym &optional soft minor-mode)
90  "Return the symbol used for SYM in MINOR-MODE.
91MINOR-MODE defaults to `gud-minor-mode.
92The symbol returned is `gud-<MINOR-MODE>-<SYM>'.
93If SOFT is non-nil, returns nil if the symbol doesn't already exist."
94  (unless (or minor-mode gud-minor-mode) (error "Gud internal error"))
95  (funcall (if soft 'intern-soft 'intern)
96	   (format "gud-%s-%s" (or minor-mode gud-minor-mode) sym)))
97
98(defun gud-val (sym &optional minor-mode)
99  "Return the value of `gud-symbol' SYM.  Default to nil."
100  (let ((sym (gud-symbol sym t minor-mode)))
101    (if (boundp sym) (symbol-value sym))))
102
103(defvar gud-running nil
104  "Non-nil if debugged program is running.
105Used to grey out relevant toolbar icons.")
106
107;; Use existing Info buffer, if possible.
108(defun gud-goto-info ()
109  "Go to relevant Emacs info node."
110  (interactive)
111  (let ((same-window-regexps same-window-regexps)
112	(display-buffer-reuse-frames t))
113    (catch 'info-found
114      (walk-windows
115       '(lambda (window)
116	  (if (eq (window-buffer window) (get-buffer "*info*"))
117	      (progn
118		(setq same-window-regexps nil)
119		(throw 'info-found nil))))
120       nil 0)
121      (select-frame (make-frame)))
122    (if (memq gud-minor-mode '(gdbmi gdba))
123	(info "(emacs)GDB Graphical Interface")
124      (info "(emacs)Debuggers"))))
125
126(defun gud-tool-bar-item-visible-no-fringe ()
127  (not (or (eq (buffer-local-value 'major-mode (window-buffer)) 'speedbar-mode)
128	   (and (memq gud-minor-mode '(gdbmi gdba))
129		(> (car (window-fringes)) 0)))))
130
131(defun gud-stop-subjob ()
132  (interactive)
133  (with-current-buffer gud-comint-buffer
134    (if (string-equal gud-target-name "emacs")
135	(comint-stop-subjob)
136      (comint-interrupt-subjob))))
137
138(easy-mmode-defmap gud-menu-map
139  '(([help]     "Info" . gud-goto-info)
140    ([tooltips] menu-item "Toggle GUD tooltips" gud-tooltip-mode
141                  :enable (and (not emacs-basic-display)
142			       (display-graphic-p)
143			       (fboundp 'x-show-tip))
144		  :visible (memq gud-minor-mode
145				'(gdbmi gdba dbx sdb xdb pdb))
146	          :button (:toggle . gud-tooltip-mode))
147    ([refresh]	"Refresh" . gud-refresh)
148    ([run]	menu-item "Run" gud-run
149                  :enable (not gud-running)
150		  :visible (memq gud-minor-mode '(gdbmi gdb dbx jdb)))
151    ([go]	menu-item (if gdb-active-process "Continue" "Run") gud-go
152		  :visible (and (not gud-running)
153				(eq gud-minor-mode 'gdba)))
154    ([stop]	menu-item "Stop" gud-stop-subjob
155		  :visible (or (not (memq gud-minor-mode '(gdba pdb)))
156			       (and gud-running
157				    (eq gud-minor-mode 'gdba))))
158    ([until]	menu-item "Continue to selection" gud-until
159                  :enable (not gud-running)
160		  :visible (and (memq gud-minor-mode '(gdbmi gdba gdb perldb))
161				(gud-tool-bar-item-visible-no-fringe)))
162    ([remove]	menu-item "Remove Breakpoint" gud-remove
163                  :enable (not gud-running)
164		  :visible (gud-tool-bar-item-visible-no-fringe))
165    ([tbreak]	menu-item "Temporary Breakpoint" gud-tbreak
166                  :enable (not gud-running)
167		  :visible (memq gud-minor-mode
168				'(gdbmi gdba gdb sdb xdb)))
169    ([break]	menu-item "Set Breakpoint" gud-break
170                  :enable (not gud-running)
171		  :visible (gud-tool-bar-item-visible-no-fringe))
172    ([up]	menu-item "Up Stack" gud-up
173		  :enable (not gud-running)
174		  :visible (memq gud-minor-mode
175				 '(gdbmi gdba gdb dbx xdb jdb pdb)))
176    ([down]	menu-item "Down Stack" gud-down
177		  :enable (not gud-running)
178		  :visible (memq gud-minor-mode
179				 '(gdbmi gdba gdb dbx xdb jdb pdb)))
180    ([pp]	menu-item "Print S-expression" gud-pp
181                  :enable (and (not gud-running)
182				  gdb-active-process)
183		  :visible (and (string-equal
184				 (buffer-local-value
185				  'gud-target-name gud-comint-buffer) "emacs")
186				(eq gud-minor-mode 'gdba)))
187    ([print*]	menu-item "Print Dereference" gud-pstar
188                  :enable (not gud-running)
189		  :visible (memq gud-minor-mode '(gdbmi gdba gdb)))
190    ([print]	menu-item "Print Expression" gud-print
191                  :enable (not gud-running))
192    ([watch]	menu-item "Watch Expression" gud-watch
193		  :enable (not gud-running)
194	  	  :visible (memq gud-minor-mode '(gdbmi gdba)))
195    ([finish]	menu-item "Finish Function" gud-finish
196                  :enable (not gud-running)
197		  :visible (memq gud-minor-mode
198				 '(gdbmi gdba gdb xdb jdb pdb)))
199    ([stepi]	menu-item "Step Instruction" gud-stepi
200                  :enable (not gud-running)
201		  :visible (memq gud-minor-mode '(gdbmi gdba gdb dbx)))
202    ([nexti]	menu-item "Next Instruction" gud-nexti
203                  :enable (not gud-running)
204		  :visible (memq gud-minor-mode '(gdbmi gdba gdb dbx)))
205    ([step]	menu-item "Step Line" gud-step
206                  :enable (not gud-running))
207    ([next]	menu-item "Next Line" gud-next
208                  :enable (not gud-running))
209    ([cont]	menu-item "Continue" gud-cont
210                  :enable (not gud-running)
211		  :visible (not (eq gud-minor-mode 'gdba))))
212  "Menu for `gud-mode'."
213  :name "Gud")
214
215(easy-mmode-defmap gud-minor-mode-map
216  (append
217     `(([menu-bar debug] . ("Gud" . ,gud-menu-map)))
218     ;; Get tool bar like functionality from the menu bar on a text only
219     ;; terminal.
220   (unless window-system
221     `(([menu-bar down]
222	. (,(propertize "down" 'face 'font-lock-doc-face) . gud-down))
223       ([menu-bar up]
224	. (,(propertize "up" 'face 'font-lock-doc-face) . gud-up))
225       ([menu-bar finish]
226	. (,(propertize "finish" 'face 'font-lock-doc-face) . gud-finish))
227       ([menu-bar step]
228	. (,(propertize "step" 'face 'font-lock-doc-face) . gud-step))
229       ([menu-bar next]
230	. (,(propertize "next" 'face 'font-lock-doc-face) . gud-next))
231       ([menu-bar until] menu-item
232	,(propertize "until" 'face 'font-lock-doc-face) gud-until
233		  :visible (memq gud-minor-mode '(gdbmi gdba gdb perldb)))
234       ([menu-bar cont] menu-item
235	,(propertize "cont" 'face 'font-lock-doc-face) gud-cont
236	:visible (not (eq gud-minor-mode 'gdba)))
237       ([menu-bar run] menu-item
238	,(propertize "run" 'face 'font-lock-doc-face) gud-run
239	:visible (memq gud-minor-mode '(gdbmi gdb dbx jdb)))
240       ([menu-bar go] menu-item
241	,(propertize " go " 'face 'font-lock-doc-face) gud-go
242	:visible (and (not gud-running)
243		      (eq gud-minor-mode 'gdba)))
244       ([menu-bar stop] menu-item
245	,(propertize "stop" 'face 'font-lock-doc-face) gud-stop-subjob
246	:visible (or gud-running
247		     (not (eq gud-minor-mode 'gdba))))
248       ([menu-bar print]
249	. (,(propertize "print" 'face 'font-lock-doc-face) . gud-print))
250       ([menu-bar tools] . undefined)
251       ([menu-bar buffer] . undefined)
252       ([menu-bar options] . undefined)
253       ([menu-bar edit] . undefined)
254       ([menu-bar file] . undefined))))
255  "Map used in visited files.")
256
257(let ((m (assq 'gud-minor-mode minor-mode-map-alist)))
258  (if m (setcdr m gud-minor-mode-map)
259    (push (cons 'gud-minor-mode gud-minor-mode-map) minor-mode-map-alist)))
260
261(defvar gud-mode-map
262  ;; Will inherit from comint-mode via define-derived-mode.
263  (make-sparse-keymap)
264  "`gud-mode' keymap.")
265
266(defvar gud-tool-bar-map
267  (if (display-graphic-p)
268      (let ((map (make-sparse-keymap)))
269	(dolist (x '((gud-break . "gud/break")
270		     (gud-remove . "gud/remove")
271		     (gud-print . "gud/print")
272		     (gud-pstar . "gud/pstar")
273		     (gud-pp . "gud/pp")
274		     (gud-watch . "gud/watch")
275		     (gud-run . "gud/run")
276		     (gud-go . "gud/go")
277		     (gud-stop-subjob . "gud/stop")
278		     (gud-cont . "gud/cont")
279		     (gud-until . "gud/until")
280		     (gud-next . "gud/next")
281		     (gud-step . "gud/step")
282		     (gud-finish . "gud/finish")
283		     (gud-nexti . "gud/nexti")
284		     (gud-stepi . "gud/stepi")
285		     (gud-up . "gud/up")
286		     (gud-down . "gud/down")
287		     (gud-goto-info . "info"))
288		   map)
289	  (tool-bar-local-item-from-menu
290	   (car x) (cdr x) map gud-minor-mode-map)))))
291
292(defun gud-file-name (f)
293  "Transform a relative file name to an absolute file name.
294Uses `gud-<MINOR-MODE>-directories' to find the source files."
295  (if (file-exists-p f) (expand-file-name f)
296    (let ((directories (gud-val 'directories))
297	  (result nil))
298      (while directories
299	(let ((path (expand-file-name f (car directories))))
300	  (if (file-exists-p path)
301	      (setq result path
302		    directories nil)))
303	(setq directories (cdr directories)))
304      result)))
305
306(defun gud-find-file (file)
307  ;; Don't get confused by double slashes in the name that comes from GDB.
308  (while (string-match "//+" file)
309    (setq file (replace-match "/" t t file)))
310  (let ((minor-mode gud-minor-mode)
311	(buf (funcall (or gud-find-file 'gud-file-name) file)))
312    (when (stringp buf)
313      (setq buf (and (file-readable-p buf) (find-file-noselect buf 'nowarn))))
314    (when buf
315      ;; Copy `gud-minor-mode' to the found buffer to turn on the menu.
316      (with-current-buffer buf
317	(set (make-local-variable 'gud-minor-mode) minor-mode)
318	(set (make-local-variable 'tool-bar-map) gud-tool-bar-map)
319	(when (and gud-tooltip-mode
320		   (memq gud-minor-mode '(gdbmi gdba)))
321	  (make-local-variable 'gdb-define-alist)
322	  (unless  gdb-define-alist (gdb-create-define-alist))
323	  (add-hook 'after-save-hook 'gdb-create-define-alist nil t))
324	(make-local-variable 'gud-keep-buffer))
325      buf)))
326
327;; ======================================================================
328;; command definition
329
330;; This macro is used below to define some basic debugger interface commands.
331;; Of course you may use `gud-def' with any other debugger command, including
332;; user defined ones.
333
334;; A macro call like (gud-def FUNC NAME KEY DOC) expands to a form
335;; which defines FUNC to send the command NAME to the debugger, gives
336;; it the docstring DOC, and binds that function to KEY in the GUD
337;; major mode.  The function is also bound in the global keymap with the
338;; GUD prefix.
339
340(defmacro gud-def (func cmd key &optional doc)
341  "Define FUNC to be a command sending STR and bound to KEY, with
342optional doc string DOC.  Certain %-escapes in the string arguments
343are interpreted specially if present.  These are:
344
345  %f -- Name (without directory) of current source file.
346  %F -- Name (without directory or extension) of current source file.
347  %d -- Directory of current source file.
348  %l -- Number of current source line.
349  %e -- Text of the C lvalue or function-call expression surrounding point.
350  %a -- Text of the hexadecimal address surrounding point.
351  %p -- Prefix argument to the command (if any) as a number.
352  %c -- Fully qualified class name derived from the expression
353        surrounding point (jdb only).
354
355  The `current' source file is the file of the current buffer (if
356we're in a C file) or the source file current at the last break or
357step (if we're in the GUD buffer).
358  The `current' line is that of the current buffer (if we're in a
359source file) or the source line number at the last break or step (if
360we're in the GUD buffer)."
361  `(progn
362     (defun ,func (arg)
363       ,@(if doc (list doc))
364       (interactive "p")
365       ,(if (stringp cmd)
366	    `(gud-call ,cmd arg)
367	  cmd))
368     ,(if key `(local-set-key ,(concat "\C-c" key) ',func))
369     ,(if key `(global-set-key (vconcat gud-key-prefix ,key) ',func))))
370
371;; Where gud-display-frame should put the debugging arrow; a cons of
372;; (filename . line-number).  This is set by the marker-filter, which scans
373;; the debugger's output for indications of the current program counter.
374(defvar gud-last-frame nil)
375
376;; Used by gud-refresh, which should cause gud-display-frame to redisplay
377;; the last frame, even if it's been called before and gud-last-frame has
378;; been set to nil.
379(defvar gud-last-last-frame nil)
380
381;; All debugger-specific information is collected here.
382;; Here's how it works, in case you ever need to add a debugger to the mode.
383;;
384;; Each entry must define the following at startup:
385;;
386;;<name>
387;; comint-prompt-regexp
388;; gud-<name>-massage-args
389;; gud-<name>-marker-filter
390;; gud-<name>-find-file
391;;
392;; The job of the massage-args method is to modify the given list of
393;; debugger arguments before running the debugger.
394;;
395;; The job of the marker-filter method is to detect file/line markers in
396;; strings and set the global gud-last-frame to indicate what display
397;; action (if any) should be triggered by the marker.  Note that only
398;; whatever the method *returns* is displayed in the buffer; thus, you
399;; can filter the debugger's output, interpreting some and passing on
400;; the rest.
401;;
402;; The job of the find-file method is to visit and return the buffer indicated
403;; by the car of gud-tag-frame.  This may be a file name, a tag name, or
404;; something else.
405
406;; ======================================================================
407;; speedbar support functions and variables.
408(eval-when-compile (require 'speedbar))	;For speedbar-with-attached-buffer.
409
410(defvar gud-last-speedbar-stackframe nil
411  "Description of the currently displayed GUD stack.
412t means that there is no stack, and we are in display-file mode.")
413
414(defvar gud-speedbar-key-map nil
415  "Keymap used when in the buffers display mode.")
416
417(defun gud-speedbar-item-info ()
418  "Display the data type of the watch expression element."
419  (let ((var (nth (- (line-number-at-pos (point)) 2) gdb-var-list)))
420    (if (nth 6 var)
421	(speedbar-message "%s: %s" (nth 6 var) (nth 3 var))
422      (speedbar-message "%s" (nth 3 var)))))
423
424(defun gud-install-speedbar-variables ()
425  "Install those variables used by speedbar to enhance gud/gdb."
426  (if gud-speedbar-key-map
427      nil
428    (setq gud-speedbar-key-map (speedbar-make-specialized-keymap))
429
430    (define-key gud-speedbar-key-map "j" 'speedbar-edit-line)
431    (define-key gud-speedbar-key-map "e" 'speedbar-edit-line)
432    (define-key gud-speedbar-key-map "\C-m" 'speedbar-edit-line)
433    (define-key gud-speedbar-key-map " " 'speedbar-toggle-line-expansion)
434    (define-key gud-speedbar-key-map "D" 'gdb-var-delete)
435    (define-key gud-speedbar-key-map "p" 'gud-pp))
436
437  (speedbar-add-expansion-list '("GUD" gud-speedbar-menu-items
438				 gud-speedbar-key-map
439				 gud-expansion-speedbar-buttons))
440
441  (add-to-list
442   'speedbar-mode-functions-list
443   '("GUD" (speedbar-item-info . gud-speedbar-item-info)
444     (speedbar-line-directory . ignore))))
445
446(defvar gud-speedbar-menu-items
447  '(["Jump to stack frame" speedbar-edit-line
448     :visible (not (memq (buffer-local-value 'gud-minor-mode gud-comint-buffer)
449		    '(gdbmi gdba)))]
450    ["Edit value" speedbar-edit-line
451     :visible (memq (buffer-local-value 'gud-minor-mode gud-comint-buffer)
452		    '(gdbmi gdba))]
453    ["Delete expression" gdb-var-delete
454     :visible (memq (buffer-local-value 'gud-minor-mode gud-comint-buffer)
455		    '(gdbmi gdba))]
456    ["Auto raise frame" gdb-speedbar-auto-raise
457     :style toggle :selected gdb-speedbar-auto-raise
458     :visible (memq (buffer-local-value 'gud-minor-mode gud-comint-buffer)
459		    '(gdbmi gdba))])
460  "Additional menu items to add to the speedbar frame.")
461
462;; Make sure our special speedbar mode is loaded
463(if (featurep 'speedbar)
464    (gud-install-speedbar-variables)
465  (add-hook 'speedbar-load-hook 'gud-install-speedbar-variables))
466
467(defun gud-expansion-speedbar-buttons (directory zero)
468  "Wrapper for call to speedbar-add-expansion-list.   DIRECTORY and
469ZERO are not used, but are required by the caller."
470  (gud-speedbar-buttons gud-comint-buffer))
471
472(defun gud-speedbar-buttons (buffer)
473  "Create a speedbar display based on the current state of GUD.
474If the GUD BUFFER is not running a supported debugger, then turn
475off the specialized speedbar mode.  BUFFER is not used, but are
476required by the caller."
477  (when (and gud-comint-buffer
478	     ;; gud-comint-buffer might be killed
479	     (buffer-name gud-comint-buffer))
480    (let* ((minor-mode (with-current-buffer buffer gud-minor-mode))
481	  (window (get-buffer-window (current-buffer) 0))
482	  (start (window-start window))
483	  (p (window-point window)))
484      (cond
485       ((memq minor-mode '(gdbmi gdba))
486	(erase-buffer)
487	(insert "Watch Expressions:\n")
488	(if gdb-speedbar-auto-raise
489	    (raise-frame speedbar-frame))
490	(let ((var-list gdb-var-list) parent)
491	  (while var-list
492	    (let* (char (depth 0) (start 0) (var (car var-list))
493			(varnum (car var)) (expr (nth 1 var))
494			(type (if (nth 3 var) (nth 3 var) " "))
495			(value (nth 4 var)) (status (nth 5 var)))
496	      (put-text-property
497	       0 (length expr) 'face font-lock-variable-name-face expr)
498	      (put-text-property
499	       0 (length type) 'face font-lock-type-face type)
500	      (while (string-match "\\." varnum start)
501		(setq depth (1+ depth)
502		      start (1+ (match-beginning 0))))
503	      (if (eq depth 0) (setq parent nil))
504	      (if (or (equal (nth 2 var) "0")
505		      (and (equal (nth 2 var) "1")
506			   (string-match "char \\*$" type)))
507		  (speedbar-make-tag-line
508		   'bracket ?? nil nil
509		   (concat expr "\t" value)
510		   (if (or parent (eq status 'out-of-scope))
511		       nil 'gdb-edit-value)
512		   nil
513		   (if gdb-show-changed-values
514		       (or parent (case status
515				    (changed 'font-lock-warning-face)
516				    (out-of-scope 'shadow)
517				    (t t)))
518		     t)
519		   depth)
520		(if (eq status 'out-of-scope) (setq parent 'shadow))
521		(if (and (nth 1 var-list)
522			 (string-match (concat varnum "\\.")
523				       (car (nth 1 var-list))))
524		    (setq char ?-)
525		  (setq char ?+))
526		(if (string-match "\\*$\\|\\*&$" type)
527		    (speedbar-make-tag-line
528		     'bracket char
529		     'gdb-speedbar-expand-node varnum
530		     (concat expr "\t" type "\t" value)
531		     (if (or parent (eq status 'out-of-scope))
532			 nil 'gdb-edit-value)
533		     nil
534		     (if gdb-show-changed-values
535			 (or parent (case status
536				      (changed 'font-lock-warning-face)
537				      (out-of-scope 'shadow)
538				      (t t)))
539		       t)
540		     depth)
541		  (speedbar-make-tag-line
542		   'bracket char
543		   'gdb-speedbar-expand-node varnum
544		   (concat expr "\t" type)
545		   nil nil
546		   (if (and (or parent status) gdb-show-changed-values)
547		       'shadow t)
548		   depth))))
549	    (setq var-list (cdr var-list)))))
550       (t (unless (and (save-excursion
551			 (goto-char (point-min))
552			 (looking-at "Current Stack:"))
553		       (equal gud-last-last-frame gud-last-speedbar-stackframe))
554	    (let ((gud-frame-list
555	    (cond ((eq minor-mode 'gdb)
556		   (gud-gdb-get-stackframe buffer))
557		  ;; Add more debuggers here!
558		  (t (speedbar-remove-localized-speedbar-support buffer)
559		     nil))))
560	      (erase-buffer)
561	      (if (not gud-frame-list)
562		  (insert "No Stack frames\n")
563		(insert "Current Stack:\n"))
564	      (dolist (frame gud-frame-list)
565		(insert (nth 1 frame) ":\n")
566		(if (= (length frame) 2)
567		(progn
568		  (speedbar-insert-button (car frame)
569					  'speedbar-directory-face
570					  nil nil nil t))
571		(speedbar-insert-button
572		 (car frame)
573		 'speedbar-file-face
574		 'speedbar-highlight-face
575		 (cond ((memq minor-mode '(gdbmi gdba gdb))
576			'gud-gdb-goto-stackframe)
577		       (t (error "Should never be here")))
578		 frame t))))
579	    (setq gud-last-speedbar-stackframe gud-last-last-frame))))
580      (set-window-start window start)
581      (set-window-point window p))))
582
583
584;; ======================================================================
585;; gdb functions
586
587;; History of argument lists passed to gdb.
588(defvar gud-gdb-history nil)
589
590(defcustom gud-gdb-command-name "gdb --annotate=3"
591  "Default command to execute an executable under the GDB debugger."
592   :type 'string
593   :group 'gud)
594
595(defvar gud-gdb-marker-regexp
596  ;; This used to use path-separator instead of ":";
597  ;; however, we found that on both Windows 32 and MSDOS
598  ;; a colon is correct here.
599  (concat "\032\032\\(.:?[^" ":" "\n]*\\)" ":"
600	  "\\([0-9]*\\)" ":" ".*\n"))
601
602;; There's no guarantee that Emacs will hand the filter the entire
603;; marker at once; it could be broken up across several strings.  We
604;; might even receive a big chunk with several markers in it.  If we
605;; receive a chunk of text which looks like it might contain the
606;; beginning of a marker, we save it here between calls to the
607;; filter.
608(defvar gud-marker-acc "")
609(make-variable-buffer-local 'gud-marker-acc)
610
611(defun gud-gdb-marker-filter (string)
612  (setq gud-marker-acc (concat gud-marker-acc string))
613  (let ((output ""))
614
615    ;; Process all the complete markers in this chunk.
616    (while (string-match gud-gdb-marker-regexp gud-marker-acc)
617      (setq
618
619       ;; Extract the frame position from the marker.
620       gud-last-frame (cons (match-string 1 gud-marker-acc)
621			    (string-to-number (match-string 2 gud-marker-acc)))
622
623       ;; Append any text before the marker to the output we're going
624       ;; to return - we don't include the marker in this text.
625       output (concat output
626		      (substring gud-marker-acc 0 (match-beginning 0)))
627
628       ;; Set the accumulator to the remaining text.
629       gud-marker-acc (substring gud-marker-acc (match-end 0))))
630
631    ;; Check for annotations and change gud-minor-mode to 'gdba if
632    ;; they are found.
633    (while (string-match "\n\032\032\\(.*\\)\n" gud-marker-acc)
634      (let ((match (match-string 1 gud-marker-acc)))
635
636	;; Pick up stopped annotation if attaching to process.
637	(if (string-equal match "stopped") (setq gdb-active-process t))
638
639	;; Using annotations, switch to gud-gdba-marker-filter.
640	(when (string-equal match "prompt")
641	  (require 'gdb-ui)
642	  (gdb-prompt nil))
643
644	(setq
645	 ;; Append any text before the marker to the output we're going
646	 ;; to return - we don't include the marker in this text.
647	 output (concat output
648			(substring gud-marker-acc 0 (match-beginning 0)))
649
650	 ;; Set the accumulator to the remaining text.
651
652	 gud-marker-acc (substring gud-marker-acc (match-end 0)))
653
654	;; Pick up any errors that occur before first prompt annotation.
655	(if (string-equal match "error-begin")
656	    (put-text-property 0 (length gud-marker-acc)
657			       'face font-lock-warning-face
658			       gud-marker-acc))))
659
660    ;; Does the remaining text look like it might end with the
661    ;; beginning of another marker?  If it does, then keep it in
662    ;; gud-marker-acc until we receive the rest of it.  Since we
663    ;; know the full marker regexp above failed, it's pretty simple to
664    ;; test for marker starts.
665    (if (string-match "\n\\(\032.*\\)?\\'" gud-marker-acc)
666	(progn
667	  ;; Everything before the potential marker start can be output.
668	  (setq output (concat output (substring gud-marker-acc
669						 0 (match-beginning 0))))
670
671	  ;; Everything after, we save, to combine with later input.
672	  (setq gud-marker-acc
673		(substring gud-marker-acc (match-beginning 0))))
674
675      (setq output (concat output gud-marker-acc)
676	    gud-marker-acc ""))
677
678    output))
679
680(easy-mmode-defmap gud-minibuffer-local-map
681  '(("\C-i" . comint-dynamic-complete-filename))
682  "Keymap for minibuffer prompting of gud startup command."
683  :inherit minibuffer-local-map)
684
685(defun gud-query-cmdline (minor-mode &optional init)
686  (let* ((hist-sym (gud-symbol 'history nil minor-mode))
687	 (cmd-name (gud-val 'command-name minor-mode)))
688    (unless (boundp hist-sym) (set hist-sym nil))
689    (read-from-minibuffer
690     (format "Run %s (like this): " minor-mode)
691     (or (car-safe (symbol-value hist-sym))
692	 (concat (or cmd-name (symbol-name minor-mode))
693		 " "
694		 (or init
695		     (let ((file nil))
696		       (dolist (f (directory-files default-directory) file)
697			 (if (and (file-executable-p f)
698				  (not (file-directory-p f))
699				  (or (not file)
700				      (file-newer-than-file-p f file)))
701			     (setq file f)))))))
702     gud-minibuffer-local-map nil
703     hist-sym)))
704
705(defvar gdb-first-prompt t)
706
707(defvar gud-filter-pending-text nil
708  "Non-nil means this is text that has been saved for later in `gud-filter'.")
709
710;;;###autoload
711(defun gdb (command-line)
712  "Run gdb on program FILE in buffer *gud-FILE*.
713The directory containing FILE becomes the initial working
714directory and source-file directory for your debugger.  By
715default this command starts GDB using a graphical interface.  See
716`gdba' for more information.
717
718To run GDB in text command mode, replace the GDB \"--annotate=3\"
719option with \"--fullname\" either in the minibuffer for the
720current Emacs session, or the custom variable
721`gud-gdb-command-name' for all future sessions.  You need to use
722text command mode to debug multiple programs within one Emacs
723session."
724  (interactive (list (gud-query-cmdline 'gdb)))
725
726  (when (and gud-comint-buffer
727	   (buffer-name gud-comint-buffer)
728	   (get-buffer-process gud-comint-buffer)
729	   (with-current-buffer gud-comint-buffer (eq gud-minor-mode 'gdba)))
730	(gdb-restore-windows)
731	(error
732	 "Multiple debugging requires restarting in text command mode"))
733
734  (gud-common-init command-line nil 'gud-gdb-marker-filter)
735  (set (make-local-variable 'gud-minor-mode) 'gdb)
736
737  (gud-def gud-break  "break %f:%l"  "\C-b" "Set breakpoint at current line.")
738  (gud-def gud-tbreak "tbreak %f:%l" "\C-t"
739	   "Set temporary breakpoint at current line.")
740  (gud-def gud-remove "clear %f:%l" "\C-d" "Remove breakpoint at current line")
741  (gud-def gud-step   "step %p"     "\C-s" "Step one source line with display.")
742  (gud-def gud-stepi  "stepi %p"    "\C-i" "Step one instruction with display.")
743  (gud-def gud-next   "next %p"     "\C-n" "Step one line (skip functions).")
744  (gud-def gud-nexti  "nexti %p" nil   "Step one instruction (skip functions).")
745  (gud-def gud-cont   "cont"     "\C-r" "Continue with display.")
746  (gud-def gud-finish "finish"   "\C-f" "Finish executing current function.")
747  (gud-def gud-jump
748	   (progn (gud-call "tbreak %f:%l") (gud-call "jump %f:%l"))
749	   "\C-j" "Set execution address to current line.")
750
751  (gud-def gud-up     "up %p"     "<" "Up N stack frames (numeric arg).")
752  (gud-def gud-down   "down %p"   ">" "Down N stack frames (numeric arg).")
753  (gud-def gud-print  "print %e"  "\C-p" "Evaluate C expression at point.")
754  (gud-def gud-pstar  "print* %e" nil
755	   "Evaluate C dereferenced pointer expression at point.")
756
757  ;; For debugging Emacs only.
758  (gud-def gud-pv "pv1 %e"      "\C-v" "Print the value of the lisp variable.")
759
760  (gud-def gud-until  "until %l" "\C-u" "Continue to current line.")
761  (gud-def gud-run    "run"	 nil    "Run the program.")
762
763  (local-set-key "\C-i" 'gud-gdb-complete-command)
764  (setq comint-prompt-regexp "^(.*gdb[+]?) *")
765  (setq paragraph-start comint-prompt-regexp)
766  (setq gdb-first-prompt t)
767  (setq gud-filter-pending-text nil)
768  (run-hooks 'gdb-mode-hook))
769
770;; One of the nice features of GDB is its impressive support for
771;; context-sensitive command completion.  We preserve that feature
772;; in the GUD buffer by using a GDB command designed just for Emacs.
773
774;; The completion process filter indicates when it is finished.
775(defvar gud-gdb-fetch-lines-in-progress)
776
777;; Since output may arrive in fragments we accumulate partials strings here.
778(defvar gud-gdb-fetch-lines-string)
779
780;; We need to know how much of the completion to chop off.
781(defvar gud-gdb-fetch-lines-break)
782
783;; The completion list is constructed by the process filter.
784(defvar gud-gdb-fetched-lines)
785
786(defun gud-gdb-complete-command (&optional command a b)
787  "Perform completion on the GDB command preceding point.
788This is implemented using the GDB `complete' command which isn't
789available with older versions of GDB."
790  (interactive)
791  (if command
792      ;; Used by gud-watch in mini-buffer.
793      (setq command (concat "p " command))
794    ;; Used in GUD buffer.
795    (let ((end (point)))
796      (setq command (buffer-substring (comint-line-beginning-position) end))))
797  (let* ((command-word
798	  ;; Find the word break.  This match will always succeed.
799	  (and (string-match "\\(\\`\\| \\)\\([^ ]*\\)\\'" command)
800	       (substring command (match-beginning 2))))
801	 (complete-list
802	  (gud-gdb-run-command-fetch-lines (concat "complete " command)
803					   (current-buffer)
804					   ;; From string-match above.
805					   (match-beginning 2))))
806    ;; Protect against old versions of GDB.
807    (and complete-list
808	 (string-match "^Undefined command: \"complete\"" (car complete-list))
809	 (error "This version of GDB doesn't support the `complete' command"))
810    ;; Sort the list like readline.
811    (setq complete-list (sort complete-list (function string-lessp)))
812    ;; Remove duplicates.
813    (let ((first complete-list)
814	  (second (cdr complete-list)))
815      (while second
816	(if (string-equal (car first) (car second))
817	    (setcdr first (setq second (cdr second)))
818	  (setq first second
819		second (cdr second)))))
820    ;; Add a trailing single quote if there is a unique completion
821    ;; and it contains an odd number of unquoted single quotes.
822    (and (= (length complete-list) 1)
823	 (let ((str (car complete-list))
824	       (pos 0)
825	       (count 0))
826	   (while (string-match "\\([^'\\]\\|\\\\'\\)*'" str pos)
827	     (setq count (1+ count)
828		   pos (match-end 0)))
829	   (and (= (mod count 2) 1)
830		(setq complete-list (list (concat str "'"))))))
831    ;; Let comint handle the rest.
832    (comint-dynamic-simple-complete command-word complete-list)))
833
834;; The completion process filter is installed temporarily to slurp the
835;; output of GDB up to the next prompt and build the completion list.
836(defun gud-gdb-fetch-lines-filter (string filter)
837  "Filter used to read the list of lines output by a command.
838STRING is the output to filter.
839It is passed through FILTER before we look at it."
840  (setq string (funcall filter string))
841  (setq string (concat gud-gdb-fetch-lines-string string))
842  (while (string-match "\n" string)
843    (push (substring string gud-gdb-fetch-lines-break (match-beginning 0))
844	  gud-gdb-fetched-lines)
845    (setq string (substring string (match-end 0))))
846  (if (string-match comint-prompt-regexp string)
847      (progn
848	(setq gud-gdb-fetch-lines-in-progress nil)
849	string)
850    (progn
851      (setq gud-gdb-fetch-lines-string string)
852      "")))
853
854;; gdb speedbar functions
855
856(defun gud-gdb-goto-stackframe (text token indent)
857  "Goto the stackframe described by TEXT, TOKEN, and INDENT."
858  (speedbar-with-attached-buffer
859   (gud-basic-call (concat "server frame " (nth 1 token)))
860   (sit-for 1)))
861
862(defvar gud-gdb-fetched-stack-frame nil
863  "Stack frames we are fetching from GDB.")
864
865;(defun gud-gdb-get-scope-data (text token indent)
866;  ;; checkdoc-params: (indent)
867;  "Fetch data associated with a stack frame, and expand/contract it.
868;Data to do this is retrieved from TEXT and TOKEN."
869;  (let ((args nil) (scope nil))
870;    (gud-gdb-run-command-fetch-lines "info args")
871;
872;    (gud-gdb-run-command-fetch-lines "info local")
873;
874;    ))
875
876(defun gud-gdb-get-stackframe (buffer)
877  "Extract the current stack frame out of the GUD GDB BUFFER."
878  (let ((newlst nil)
879	(fetched-stack-frame-list
880	 (gud-gdb-run-command-fetch-lines "server backtrace" buffer)))
881    (if (and (car fetched-stack-frame-list)
882	     (string-match "No stack" (car fetched-stack-frame-list)))
883	;; Go into some other mode???
884	nil
885      (dolist (e fetched-stack-frame-list)
886	(let ((name nil) (num nil))
887	  (if (not (or
888		    (string-match "^#\\([0-9]+\\) +[0-9a-fx]+ in \\([:0-9a-zA-Z_]+\\) (" e)
889		    (string-match "^#\\([0-9]+\\) +\\([:0-9a-zA-Z_]+\\) (" e)))
890	      (if (not (string-match
891			"at \\([-0-9a-zA-Z_.]+\\):\\([0-9]+\\)$" e))
892		  nil
893		(setcar newlst
894			(list (nth 0 (car newlst))
895			      (nth 1 (car newlst))
896			      (match-string 1 e)
897			      (match-string 2 e))))
898	    (setq num (match-string 1 e)
899		  name (match-string 2 e))
900	    (setq newlst
901		  (cons
902		   (if (string-match
903			"at \\([-0-9a-zA-Z_.]+\\):\\([0-9]+\\)$" e)
904		       (list name num (match-string 1 e)
905			     (match-string 2 e))
906		     (list name num))
907		   newlst)))))
908      (nreverse newlst))))
909
910;(defun gud-gdb-selected-frame-info (buffer)
911;  "Learn GDB information for the currently selected stack frame in BUFFER."
912;  )
913
914(defun gud-gdb-run-command-fetch-lines (command buffer &optional skip)
915  "Run COMMAND, and return the list of lines it outputs.
916BUFFER is the current buffer which may be the GUD buffer in which to run.
917SKIP is the number of chars to skip on each lines, it defaults to 0."
918  (with-current-buffer gud-comint-buffer
919    (if (and (eq gud-comint-buffer buffer)
920	     (save-excursion
921	       (goto-char (point-max))
922	       (forward-line 0)
923	       (not (looking-at comint-prompt-regexp))))
924	nil
925      ;; Much of this copied from GDB complete, but I'm grabbing the stack
926      ;; frame instead.
927      (let ((gud-gdb-fetch-lines-in-progress t)
928	    (gud-gdb-fetched-lines nil)
929	    (gud-gdb-fetch-lines-string nil)
930	    (gud-gdb-fetch-lines-break (or skip 0))
931	    (gud-marker-filter
932	     `(lambda (string)
933		(gud-gdb-fetch-lines-filter string ',gud-marker-filter))))
934	;; Issue the command to GDB.
935	(gud-basic-call command)
936	;; Slurp the output.
937	(while gud-gdb-fetch-lines-in-progress
938	  (accept-process-output (get-buffer-process gud-comint-buffer)))
939	(nreverse gud-gdb-fetched-lines)))))
940
941
942;; ======================================================================
943;; sdb functions
944
945;; History of argument lists passed to sdb.
946(defvar gud-sdb-history nil)
947
948(defvar gud-sdb-needs-tags (not (file-exists-p "/var"))
949  "If nil, we're on a System V Release 4 and don't need the tags hack.")
950
951(defvar gud-sdb-lastfile nil)
952
953(defun gud-sdb-marker-filter (string)
954  (setq gud-marker-acc
955	(if gud-marker-acc (concat gud-marker-acc string) string))
956  (let (start)
957    ;; Process all complete markers in this chunk
958    (while
959	(cond
960	 ;; System V Release 3.2 uses this format
961	 ((string-match "\\(^\\|\n\\)\\*?\\(0x\\w* in \\)?\\([^:\n]*\\):\\([0-9]*\\):.*\n"
962			gud-marker-acc start)
963	  (setq gud-last-frame
964		(cons (match-string 3 gud-marker-acc)
965		      (string-to-number (match-string 4 gud-marker-acc)))))
966	 ;; System V Release 4.0 quite often clumps two lines together
967	 ((string-match "^\\(BREAKPOINT\\|STEPPED\\) process [0-9]+ function [^ ]+ in \\(.+\\)\n\\([0-9]+\\):"
968			gud-marker-acc start)
969	  (setq gud-sdb-lastfile (match-string 2 gud-marker-acc))
970	  (setq gud-last-frame
971		(cons gud-sdb-lastfile
972		      (string-to-number (match-string 3 gud-marker-acc)))))
973	 ;; System V Release 4.0
974	 ((string-match "^\\(BREAKPOINT\\|STEPPED\\) process [0-9]+ function [^ ]+ in \\(.+\\)\n"
975			gud-marker-acc start)
976	  (setq gud-sdb-lastfile (match-string 2 gud-marker-acc)))
977	 ((and gud-sdb-lastfile (string-match "^\\([0-9]+\\):"
978					      gud-marker-acc start))
979	       (setq gud-last-frame
980		     (cons gud-sdb-lastfile
981			   (string-to-number (match-string 1 gud-marker-acc)))))
982	 (t
983	  (setq gud-sdb-lastfile nil)))
984      (setq start (match-end 0)))
985
986    ;; Search for the last incomplete line in this chunk
987    (while (string-match "\n" gud-marker-acc start)
988      (setq start (match-end 0)))
989
990    ;; If we have an incomplete line, store it in gud-marker-acc.
991    (setq gud-marker-acc (substring gud-marker-acc (or start 0))))
992  string)
993
994(defun gud-sdb-find-file (f)
995  (if gud-sdb-needs-tags (find-tag-noselect f) (find-file-noselect f)))
996
997;;;###autoload
998(defun sdb (command-line)
999  "Run sdb on program FILE in buffer *gud-FILE*.
1000The directory containing FILE becomes the initial working directory
1001and source-file directory for your debugger."
1002  (interactive (list (gud-query-cmdline 'sdb)))
1003
1004  (if gud-sdb-needs-tags (require 'etags))
1005  (if (and gud-sdb-needs-tags
1006	   (not (and (boundp 'tags-file-name)
1007		     (stringp tags-file-name)
1008		     (file-exists-p tags-file-name))))
1009      (error "The sdb support requires a valid tags table to work"))
1010
1011  (gud-common-init command-line nil 'gud-sdb-marker-filter 'gud-sdb-find-file)
1012  (set (make-local-variable 'gud-minor-mode) 'sdb)
1013
1014  (gud-def gud-break  "%l b" "\C-b"   "Set breakpoint at current line.")
1015  (gud-def gud-tbreak "%l c" "\C-t"   "Set temporary breakpoint at current line.")
1016  (gud-def gud-remove "%l d" "\C-d"   "Remove breakpoint at current line")
1017  (gud-def gud-step   "s %p" "\C-s"   "Step one source line with display.")
1018  (gud-def gud-stepi  "i %p" "\C-i"   "Step one instruction with display.")
1019  (gud-def gud-next   "S %p" "\C-n"   "Step one line (skip functions).")
1020  (gud-def gud-cont   "c"    "\C-r"   "Continue with display.")
1021  (gud-def gud-print  "%e/"  "\C-p"   "Evaluate C expression at point.")
1022
1023  (setq comint-prompt-regexp  "\\(^\\|\n\\)\\*")
1024  (setq paragraph-start comint-prompt-regexp)
1025  (run-hooks 'sdb-mode-hook)
1026  )
1027
1028;; ======================================================================
1029;; dbx functions
1030
1031;; History of argument lists passed to dbx.
1032(defvar gud-dbx-history nil)
1033
1034(defcustom gud-dbx-directories nil
1035  "*A list of directories that dbx should search for source code.
1036If nil, only source files in the program directory
1037will be known to dbx.
1038
1039The file names should be absolute, or relative to the directory
1040containing the executable being debugged."
1041  :type '(choice (const :tag "Current Directory" nil)
1042		 (repeat :value ("")
1043			 directory))
1044  :group 'gud)
1045
1046(defun gud-dbx-massage-args (file args)
1047  (nconc (let ((directories gud-dbx-directories)
1048	       (result nil))
1049	   (while directories
1050	     (setq result (cons (car directories) (cons "-I" result)))
1051	     (setq directories (cdr directories)))
1052	   (nreverse result))
1053	 args))
1054
1055(defun gud-dbx-marker-filter (string)
1056  (setq gud-marker-acc (if gud-marker-acc (concat gud-marker-acc string) string))
1057
1058  (let (start)
1059    ;; Process all complete markers in this chunk.
1060    (while (or (string-match
1061		"stopped in .* at line \\([0-9]*\\) in file \"\\([^\"]*\\)\""
1062		gud-marker-acc start)
1063	       (string-match
1064		"signal .* in .* at line \\([0-9]*\\) in file \"\\([^\"]*\\)\""
1065		gud-marker-acc start))
1066      (setq gud-last-frame
1067	    (cons (match-string 2 gud-marker-acc)
1068		  (string-to-number (match-string 1 gud-marker-acc)))
1069	    start (match-end 0)))
1070
1071    ;; Search for the last incomplete line in this chunk
1072    (while (string-match "\n" gud-marker-acc start)
1073      (setq start (match-end 0)))
1074
1075    ;; If the incomplete line APPEARS to begin with another marker, keep it
1076    ;; in the accumulator.  Otherwise, clear the accumulator to avoid an
1077    ;; unnecessary concat during the next call.
1078    (setq gud-marker-acc
1079	  (if (string-match "\\(stopped\\|signal\\)" gud-marker-acc start)
1080	      (substring gud-marker-acc (match-beginning 0))
1081	    nil)))
1082  string)
1083
1084;; Functions for Mips-style dbx.  Given the option `-emacs', documented in
1085;; OSF1, not necessarily elsewhere, it produces markers similar to gdb's.
1086(defvar gud-mips-p
1087  (or (string-match "^mips-[^-]*-ultrix" system-configuration)
1088      ;; We haven't tested gud on this system:
1089      (string-match "^mips-[^-]*-riscos" system-configuration)
1090      ;; It's documented on OSF/1.3
1091      (string-match "^mips-[^-]*-osf1" system-configuration)
1092      (string-match "^alpha[^-]*-[^-]*-osf" system-configuration))
1093  "Non-nil to assume the MIPS/OSF dbx conventions (argument `-emacs').")
1094
1095(defvar gud-dbx-command-name
1096  (concat "dbx" (if gud-mips-p " -emacs")))
1097
1098;; This is just like the gdb one except for the regexps since we need to cope
1099;; with an optional breakpoint number in [] before the ^Z^Z
1100(defun gud-mipsdbx-marker-filter (string)
1101  (setq gud-marker-acc (concat gud-marker-acc string))
1102  (let ((output ""))
1103
1104    ;; Process all the complete markers in this chunk.
1105    (while (string-match
1106	    ;; This is like th gdb marker but with an optional
1107	    ;; leading break point number like `[1] '
1108	    "[][ 0-9]*\032\032\\([^:\n]*\\):\\([0-9]*\\):.*\n"
1109	    gud-marker-acc)
1110      (setq
1111
1112       ;; Extract the frame position from the marker.
1113       gud-last-frame
1114       (cons (match-string 1 gud-marker-acc)
1115	     (string-to-number (match-string 2 gud-marker-acc)))
1116
1117       ;; Append any text before the marker to the output we're going
1118       ;; to return - we don't include the marker in this text.
1119       output (concat output
1120		      (substring gud-marker-acc 0 (match-beginning 0)))
1121
1122       ;; Set the accumulator to the remaining text.
1123       gud-marker-acc (substring gud-marker-acc (match-end 0))))
1124
1125    ;; Does the remaining text look like it might end with the
1126    ;; beginning of another marker?  If it does, then keep it in
1127    ;; gud-marker-acc until we receive the rest of it.  Since we
1128    ;; know the full marker regexp above failed, it's pretty simple to
1129    ;; test for marker starts.
1130    (if (string-match "[][ 0-9]*\032.*\\'" gud-marker-acc)
1131	(progn
1132	  ;; Everything before the potential marker start can be output.
1133	  (setq output (concat output (substring gud-marker-acc
1134						 0 (match-beginning 0))))
1135
1136	  ;; Everything after, we save, to combine with later input.
1137	  (setq gud-marker-acc
1138		(substring gud-marker-acc (match-beginning 0))))
1139
1140      (setq output (concat output gud-marker-acc)
1141	    gud-marker-acc ""))
1142
1143    output))
1144
1145;; The dbx in IRIX is a pain.  It doesn't print the file name when
1146;; stopping at a breakpoint (but you do get it from the `up' and
1147;; `down' commands...).  The only way to extract the information seems
1148;; to be with a `file' command, although the current line number is
1149;; available in $curline.  Thus we have to look for output which
1150;; appears to indicate a breakpoint.  Then we prod the dbx sub-process
1151;; to output the information we want with a combination of the
1152;; `printf' and `file' commands as a pseudo marker which we can
1153;; recognise next time through the marker-filter.  This would be like
1154;; the gdb marker but you can't get the file name without a newline...
1155;; Note that gud-remove won't work since Irix dbx expects a breakpoint
1156;; number rather than a line number etc.  Maybe this could be made to
1157;; work by listing all the breakpoints and picking the one(s) with the
1158;; correct line number, but life's too short.
1159;;   d.love@dl.ac.uk (Dave Love) can be blamed for this
1160
1161(defvar gud-irix-p
1162  (and (string-match "^mips-[^-]*-irix" system-configuration)
1163       (not (string-match "irix[6-9]\\.[1-9]" system-configuration)))
1164  "Non-nil to assume the interface appropriate for IRIX dbx.
1165This works in IRIX 4, 5 and 6, but `gud-dbx-use-stopformat-p' provides
1166a better solution in 6.1 upwards.")
1167(defvar gud-dbx-use-stopformat-p
1168  (string-match "irix[6-9]\\.[1-9]" system-configuration)
1169  "Non-nil to use the dbx feature present at least from Irix 6.1
1170  whereby $stopformat=1 produces an output format compatiable with
1171  `gud-dbx-marker-filter'.")
1172;; [Irix dbx seems to be a moving target.  The dbx output changed
1173;; subtly sometime between OS v4.0.5 and v5.2 so that, for instance,
1174;; the output from `up' is no longer spotted by gud (and it's probably
1175;; not distinctive enough to try to match it -- use C-<, C->
1176;; exclusively) .  For 5.3 and 6.0, the $curline variable changed to
1177;; `long long'(why?!), so the printf stuff needed changing.  The line
1178;; number was cast to `long' as a compromise between the new `long
1179;; long' and the original `int'.  This is reported not to work in 6.2,
1180;; so it's changed back to int -- don't make your sources too long.
1181;; From Irix6.1 (but not 6.0?) dbx supports an undocumented feature
1182;; whereby `set $stopformat=1' reportedly produces output compatible
1183;; with `gud-dbx-marker-filter', which we prefer.
1184
1185;; The process filter is also somewhat
1186;; unreliable, sometimes not spotting the markers; I don't know
1187;; whether there's anything that can be done about that.  It would be
1188;; much better if SGI could be persuaded to (re?)instate the MIPS
1189;; -emacs flag for gdb-like output (which ought to be possible as most
1190;; of the communication I've had over it has been from sgi.com).]
1191
1192;; this filter is influenced by the xdb one rather than the gdb one
1193(defun gud-irixdbx-marker-filter (string)
1194  (let (result (case-fold-search nil))
1195    (if (or (string-match comint-prompt-regexp string)
1196	    (string-match ".*\012" string))
1197	(setq result (concat gud-marker-acc string)
1198	      gud-marker-acc "")
1199      (setq gud-marker-acc (concat gud-marker-acc string)))
1200    (if result
1201	(cond
1202	 ;; look for breakpoint or signal indication e.g.:
1203	 ;; [2] Process  1267 (pplot) stopped at [params:338 ,0x400ec0]
1204	 ;; Process  1281 (pplot) stopped at [params:339 ,0x400ec8]
1205	 ;; Process  1270 (pplot) Floating point exception [._read._read:16 ,0x452188]
1206	 ((string-match
1207	   "^\\(\\[[0-9]+] \\)?Process +[0-9]+ ([^)]*) [^[]+\\[[^]\n]*]\n"
1208	   result)
1209	  ;; prod dbx into printing out the line number and file
1210	  ;; name in a form we can grok as below
1211	  (process-send-string (get-buffer-process gud-comint-buffer)
1212			       "printf \"\032\032%1d:\",(int)$curline;file\n"))
1213	 ;; look for result of, say, "up" e.g.:
1214	 ;; .pplot.pplot(0x800) ["src/pplot.f":261, 0x400c7c]
1215	 ;; (this will also catch one of the lines printed by "where")
1216	 ((string-match
1217	   "^[^ ][^[]*\\[\"\\([^\"]+\\)\":\\([0-9]+\\), [^]]+]\n"
1218	   result)
1219	  (let ((file (match-string 1 result)))
1220	    (if (file-exists-p file)
1221		(setq gud-last-frame
1222		      (cons (match-string 1 result)
1223			    (string-to-number (match-string 2 result))))))
1224	  result)
1225	 ((string-match			; kluged-up marker as above
1226	   "\032\032\\([0-9]*\\):\\(.*\\)\n" result)
1227	  (let ((file (gud-file-name (match-string 2 result))))
1228	    (if (and file (file-exists-p file))
1229		(setq gud-last-frame
1230		      (cons file
1231			    (string-to-number (match-string 1 result))))))
1232	  (setq result (substring result 0 (match-beginning 0))))))
1233    (or result "")))
1234
1235(defvar gud-dgux-p (string-match "-dgux" system-configuration)
1236  "Non-nil means to assume the interface approriate for DG/UX dbx.
1237This was tested using R4.11.")
1238
1239;; There are a couple of differences between DG's dbx output and normal
1240;; dbx output which make it nontrivial to integrate this into the
1241;; standard dbx-marker-filter (mainly, there are a different number of
1242;; backreferences).  The markers look like:
1243;;
1244;;     (0) Stopped at line 10, routine main(argc=1, argv=0xeffff0e0), file t.c
1245;;
1246;; from breakpoints (the `(0)' there isn't constant, it's the breakpoint
1247;; number), and
1248;;
1249;;     Stopped at line 13, routine main(argc=1, argv=0xeffff0e0), file t.c
1250;;
1251;; from signals and
1252;;
1253;;     Frame 21, line 974, routine command_loop(), file keyboard.c
1254;;
1255;; from up/down/where.
1256
1257(defun gud-dguxdbx-marker-filter (string)
1258  (setq gud-marker-acc (if gud-marker-acc
1259			   (concat gud-marker-acc string)
1260			 string))
1261  (let ((re (concat "^\\(\\(([0-9]+) \\)?Stopped at\\|Frame [0-9]+,\\)"
1262		    " line \\([0-9]+\\), routine .*, file \\([^ \t\n]+\\)"))
1263	start)
1264    ;; Process all complete markers in this chunk.
1265    (while (string-match re gud-marker-acc start)
1266      (setq gud-last-frame
1267	    (cons (match-string 4 gud-marker-acc)
1268		  (string-to-number (match-string 3 gud-marker-acc)))
1269	    start (match-end 0)))
1270
1271    ;; Search for the last incomplete line in this chunk
1272    (while (string-match "\n" gud-marker-acc start)
1273      (setq start (match-end 0)))
1274
1275    ;; If the incomplete line APPEARS to begin with another marker, keep it
1276    ;; in the accumulator.  Otherwise, clear the accumulator to avoid an
1277    ;; unnecessary concat during the next call.
1278    (setq gud-marker-acc
1279	  (if (string-match "Stopped\\|Frame" gud-marker-acc start)
1280	      (substring gud-marker-acc (match-beginning 0))
1281	    nil)))
1282  string)
1283
1284;;;###autoload
1285(defun dbx (command-line)
1286  "Run dbx on program FILE in buffer *gud-FILE*.
1287The directory containing FILE becomes the initial working directory
1288and source-file directory for your debugger."
1289  (interactive (list (gud-query-cmdline 'dbx)))
1290
1291  (cond
1292   (gud-mips-p
1293    (gud-common-init command-line nil 'gud-mipsdbx-marker-filter))
1294   (gud-irix-p
1295    (gud-common-init command-line 'gud-dbx-massage-args
1296		     'gud-irixdbx-marker-filter))
1297   (gud-dgux-p
1298    (gud-common-init command-line 'gud-dbx-massage-args
1299		     'gud-dguxdbx-marker-filter))
1300   (t
1301    (gud-common-init command-line 'gud-dbx-massage-args
1302		     'gud-dbx-marker-filter)))
1303
1304  (set (make-local-variable 'gud-minor-mode) 'dbx)
1305
1306  (cond
1307   (gud-mips-p
1308    (gud-def gud-up	"up %p"	  "<" "Up (numeric arg) stack frames.")
1309    (gud-def gud-down	"down %p" ">" "Down (numeric arg) stack frames.")
1310    (gud-def gud-break  "stop at \"%f\":%l"
1311				  "\C-b" "Set breakpoint at current line.")
1312    (gud-def gud-finish "return"  "\C-f" "Finish executing current function."))
1313   (gud-irix-p
1314    (gud-def gud-break  "stop at \"%d%f\":%l"
1315				  "\C-b" "Set breakpoint at current line.")
1316    (gud-def gud-finish "return"  "\C-f" "Finish executing current function.")
1317    (gud-def gud-up	"up %p; printf \"\032\032%1d:\",(int)$curline;file\n"
1318	     "<" "Up (numeric arg) stack frames.")
1319    (gud-def gud-down "down %p; printf \"\032\032%1d:\",(int)$curline;file\n"
1320	     ">" "Down (numeric arg) stack frames.")
1321    ;; Make dbx give out the source location info that we need.
1322    (process-send-string (get-buffer-process gud-comint-buffer)
1323			 "printf \"\032\032%1d:\",(int)$curline;file\n"))
1324   (t
1325    (gud-def gud-up	"up %p"   "<" "Up (numeric arg) stack frames.")
1326    (gud-def gud-down	"down %p" ">" "Down (numeric arg) stack frames.")
1327    (gud-def gud-break "file \"%d%f\"\nstop at %l"
1328				  "\C-b" "Set breakpoint at current line.")
1329    (if gud-dbx-use-stopformat-p
1330	(process-send-string (get-buffer-process gud-comint-buffer)
1331			     "set $stopformat=1\n"))))
1332
1333  (gud-def gud-remove "clear %l"  "\C-d" "Remove breakpoint at current line")
1334  (gud-def gud-step   "step %p"   "\C-s" "Step one line with display.")
1335  (gud-def gud-stepi  "stepi %p"  "\C-i" "Step one instruction with display.")
1336  (gud-def gud-next   "next %p"   "\C-n" "Step one line (skip functions).")
1337  (gud-def gud-nexti  "nexti %p"   nil  "Step one instruction (skip functions).")
1338  (gud-def gud-cont   "cont"      "\C-r" "Continue with display.")
1339  (gud-def gud-print  "print %e"  "\C-p" "Evaluate C expression at point.")
1340  (gud-def gud-run    "run"	     nil    "Run the program.")
1341
1342  (setq comint-prompt-regexp  "^[^)\n]*dbx) *")
1343  (setq paragraph-start comint-prompt-regexp)
1344  (run-hooks 'dbx-mode-hook)
1345  )
1346
1347;; ======================================================================
1348;; xdb (HP PARISC debugger) functions
1349
1350;; History of argument lists passed to xdb.
1351(defvar gud-xdb-history nil)
1352
1353(defcustom gud-xdb-directories nil
1354  "*A list of directories that xdb should search for source code.
1355If nil, only source files in the program directory
1356will be known to xdb.
1357
1358The file names should be absolute, or relative to the directory
1359containing the executable being debugged."
1360  :type '(choice (const :tag "Current Directory" nil)
1361		 (repeat :value ("")
1362			 directory))
1363  :group 'gud)
1364
1365(defun gud-xdb-massage-args (file args)
1366  (nconc (let ((directories gud-xdb-directories)
1367	       (result nil))
1368	   (while directories
1369	     (setq result (cons (car directories) (cons "-d" result)))
1370	     (setq directories (cdr directories)))
1371	   (nreverse result))
1372	 args))
1373
1374;; xdb does not print the lines all at once, so we have to accumulate them
1375(defun gud-xdb-marker-filter (string)
1376  (let (result)
1377    (if (or (string-match comint-prompt-regexp string)
1378	    (string-match ".*\012" string))
1379	(setq result (concat gud-marker-acc string)
1380	      gud-marker-acc "")
1381      (setq gud-marker-acc (concat gud-marker-acc string)))
1382    (if result
1383	(if (or (string-match "\\([^\n \t:]+\\): [^:]+: \\([0-9]+\\)[: ]"
1384			      result)
1385                (string-match "[^: \t]+:[ \t]+\\([^:]+\\): [^:]+: \\([0-9]+\\):"
1386                              result))
1387            (let ((line (string-to-number (match-string 2 result)))
1388                  (file (gud-file-name (match-string 1 result))))
1389              (if file
1390                  (setq gud-last-frame (cons file line))))))
1391    (or result "")))
1392
1393;;;###autoload
1394(defun xdb (command-line)
1395  "Run xdb on program FILE in buffer *gud-FILE*.
1396The directory containing FILE becomes the initial working directory
1397and source-file directory for your debugger.
1398
1399You can set the variable `gud-xdb-directories' to a list of program source
1400directories if your program contains sources from more than one directory."
1401  (interactive (list (gud-query-cmdline 'xdb)))
1402
1403  (gud-common-init command-line 'gud-xdb-massage-args
1404		   'gud-xdb-marker-filter)
1405  (set (make-local-variable 'gud-minor-mode) 'xdb)
1406
1407  (gud-def gud-break  "b %f:%l"    "\C-b" "Set breakpoint at current line.")
1408  (gud-def gud-tbreak "b %f:%l\\t" "\C-t"
1409	   "Set temporary breakpoint at current line.")
1410  (gud-def gud-remove "db"         "\C-d" "Remove breakpoint at current line")
1411  (gud-def gud-step   "s %p"       "\C-s" "Step one line with display.")
1412  (gud-def gud-next   "S %p"       "\C-n" "Step one line (skip functions).")
1413  (gud-def gud-cont   "c"          "\C-r" "Continue with display.")
1414  (gud-def gud-up     "up %p"      "<"    "Up (numeric arg) stack frames.")
1415  (gud-def gud-down   "down %p"    ">"    "Down (numeric arg) stack frames.")
1416  (gud-def gud-finish "bu\\t"      "\C-f" "Finish executing current function.")
1417  (gud-def gud-print  "p %e"       "\C-p" "Evaluate C expression at point.")
1418
1419  (setq comint-prompt-regexp  "^>")
1420  (setq paragraph-start comint-prompt-regexp)
1421  (run-hooks 'xdb-mode-hook))
1422
1423;; ======================================================================
1424;; perldb functions
1425
1426;; History of argument lists passed to perldb.
1427(defvar gud-perldb-history nil)
1428
1429(defun gud-perldb-massage-args (file args)
1430  "Convert a command line as would be typed normally to run perldb
1431into one that invokes an Emacs-enabled debugging session.
1432\"-emacs\" is inserted where it will be $ARGV[0] (see perl5db.pl)."
1433  ;; FIXME: what if the command is `make perldb' and doesn't accept those extra
1434  ;; arguments ?
1435  (let* ((new-args nil)
1436	 (seen-e nil)
1437	 (shift (lambda () (push (pop args) new-args))))
1438
1439    ;; Pass all switches and -e scripts through.
1440    (while (and args
1441		(string-match "^-" (car args))
1442		(not (equal "-" (car args)))
1443		(not (equal "--" (car args))))
1444      (when (equal "-e" (car args))
1445	;; -e goes with the next arg, so shift one extra.
1446	(or (funcall shift)
1447	    ;; -e as the last arg is an error in Perl.
1448	    (error "No code specified for -e"))
1449	(setq seen-e t))
1450      (funcall shift))
1451
1452    (unless seen-e
1453      (if (or (not args)
1454	      (string-match "^-" (car args)))
1455	  (error "Can't use stdin as the script to debug"))
1456      ;; This is the program name.
1457      (funcall shift))
1458
1459    ;; If -e specified, make sure there is a -- so -emacs is not taken
1460    ;; as -e macs.
1461    (if (and args (equal "--" (car args)))
1462	(funcall shift)
1463      (and seen-e (push "--" new-args)))
1464
1465    (push "-emacs" new-args)
1466    (while args
1467      (funcall shift))
1468
1469    (nreverse new-args)))
1470
1471;; There's no guarantee that Emacs will hand the filter the entire
1472;; marker at once; it could be broken up across several strings.  We
1473;; might even receive a big chunk with several markers in it.  If we
1474;; receive a chunk of text which looks like it might contain the
1475;; beginning of a marker, we save it here between calls to the
1476;; filter.
1477(defun gud-perldb-marker-filter (string)
1478  (setq gud-marker-acc (concat gud-marker-acc string))
1479  (let ((output ""))
1480
1481    ;; Process all the complete markers in this chunk.
1482    (while (string-match "\032\032\\(\\([a-zA-Z]:\\)?[^:\n]*\\):\\([0-9]*\\):.*\n"
1483			 gud-marker-acc)
1484      (setq
1485
1486       ;; Extract the frame position from the marker.
1487       gud-last-frame
1488       (cons (match-string 1 gud-marker-acc)
1489	     (string-to-number (match-string 3 gud-marker-acc)))
1490
1491       ;; Append any text before the marker to the output we're going
1492       ;; to return - we don't include the marker in this text.
1493       output (concat output
1494		      (substring gud-marker-acc 0 (match-beginning 0)))
1495
1496       ;; Set the accumulator to the remaining text.
1497       gud-marker-acc (substring gud-marker-acc (match-end 0))))
1498
1499    ;; Does the remaining text look like it might end with the
1500    ;; beginning of another marker?  If it does, then keep it in
1501    ;; gud-marker-acc until we receive the rest of it.  Since we
1502    ;; know the full marker regexp above failed, it's pretty simple to
1503    ;; test for marker starts.
1504    (if (string-match "\032.*\\'" gud-marker-acc)
1505	(progn
1506	  ;; Everything before the potential marker start can be output.
1507	  (setq output (concat output (substring gud-marker-acc
1508						 0 (match-beginning 0))))
1509
1510	  ;; Everything after, we save, to combine with later input.
1511	  (setq gud-marker-acc
1512		(substring gud-marker-acc (match-beginning 0))))
1513
1514      (setq output (concat output gud-marker-acc)
1515	    gud-marker-acc ""))
1516
1517    output))
1518
1519(defcustom gud-perldb-command-name "perl -d"
1520  "Default command to execute a Perl script under debugger."
1521  :type 'string
1522  :group 'gud)
1523
1524;;;###autoload
1525(defun perldb (command-line)
1526  "Run perldb on program FILE in buffer *gud-FILE*.
1527The directory containing FILE becomes the initial working directory
1528and source-file directory for your debugger."
1529  (interactive
1530   (list (gud-query-cmdline 'perldb
1531			    (concat (or (buffer-file-name) "-e 0") " "))))
1532
1533  (gud-common-init command-line 'gud-perldb-massage-args
1534		   'gud-perldb-marker-filter)
1535  (set (make-local-variable 'gud-minor-mode) 'perldb)
1536
1537  (gud-def gud-break  "b %l"         "\C-b" "Set breakpoint at current line.")
1538  (gud-def gud-remove "B %l"         "\C-d" "Remove breakpoint at current line")
1539  (gud-def gud-step   "s"            "\C-s" "Step one source line with display.")
1540  (gud-def gud-next   "n"            "\C-n" "Step one line (skip functions).")
1541  (gud-def gud-cont   "c"            "\C-r" "Continue with display.")
1542;  (gud-def gud-finish "finish"       "\C-f" "Finish executing current function.")
1543;  (gud-def gud-up     "up %p"        "<" "Up N stack frames (numeric arg).")
1544;  (gud-def gud-down   "down %p"      ">" "Down N stack frames (numeric arg).")
1545  (gud-def gud-print  "p %e"          "\C-p" "Evaluate perl expression at point.")
1546  (gud-def gud-until  "c %l"          "\C-u" "Continue to current line.")
1547
1548
1549  (setq comint-prompt-regexp "^  DB<+[0-9]+>+ ")
1550  (setq paragraph-start comint-prompt-regexp)
1551  (run-hooks 'perldb-mode-hook))
1552
1553;; ======================================================================
1554;; pdb (Python debugger) functions
1555
1556;; History of argument lists passed to pdb.
1557(defvar gud-pdb-history nil)
1558
1559;; Last group is for return value, e.g. "> test.py(2)foo()->None"
1560;; Either file or function name may be omitted: "> <string>(0)?()"
1561(defvar gud-pdb-marker-regexp
1562  "^> \\([-a-zA-Z0-9_/.:\\]*\\|<string>\\)(\\([0-9]+\\))\\([a-zA-Z0-9_]*\\|\\?\\|<module>\\)()\\(->[^\n]*\\)?\n")
1563(defvar gud-pdb-marker-regexp-file-group 1)
1564(defvar gud-pdb-marker-regexp-line-group 2)
1565(defvar gud-pdb-marker-regexp-fnname-group 3)
1566
1567(defvar gud-pdb-marker-regexp-start "^> ")
1568
1569;; There's no guarantee that Emacs will hand the filter the entire
1570;; marker at once; it could be broken up across several strings.  We
1571;; might even receive a big chunk with several markers in it.  If we
1572;; receive a chunk of text which looks like it might contain the
1573;; beginning of a marker, we save it here between calls to the
1574;; filter.
1575(defun gud-pdb-marker-filter (string)
1576  (setq gud-marker-acc (concat gud-marker-acc string))
1577  (let ((output ""))
1578
1579    ;; Process all the complete markers in this chunk.
1580    (while (string-match gud-pdb-marker-regexp gud-marker-acc)
1581      (setq
1582
1583       ;; Extract the frame position from the marker.
1584       gud-last-frame
1585       (let ((file (match-string gud-pdb-marker-regexp-file-group
1586				 gud-marker-acc))
1587	     (line (string-to-number
1588		    (match-string gud-pdb-marker-regexp-line-group
1589				  gud-marker-acc))))
1590	 (if (string-equal file "<string>")
1591	     gud-last-frame
1592	   (cons file line)))
1593
1594       ;; Output everything instead of the below
1595       output (concat output (substring gud-marker-acc 0 (match-end 0)))
1596;;	  ;; Append any text before the marker to the output we're going
1597;;	  ;; to return - we don't include the marker in this text.
1598;;	  output (concat output
1599;;		      (substring gud-marker-acc 0 (match-beginning 0)))
1600
1601       ;; Set the accumulator to the remaining text.
1602       gud-marker-acc (substring gud-marker-acc (match-end 0))))
1603
1604    ;; Does the remaining text look like it might end with the
1605    ;; beginning of another marker?  If it does, then keep it in
1606    ;; gud-marker-acc until we receive the rest of it.  Since we
1607    ;; know the full marker regexp above failed, it's pretty simple to
1608    ;; test for marker starts.
1609    (if (string-match gud-pdb-marker-regexp-start gud-marker-acc)
1610	(progn
1611	  ;; Everything before the potential marker start can be output.
1612	  (setq output (concat output (substring gud-marker-acc
1613						 0 (match-beginning 0))))
1614
1615	  ;; Everything after, we save, to combine with later input.
1616	  (setq gud-marker-acc
1617		(substring gud-marker-acc (match-beginning 0))))
1618
1619      (setq output (concat output gud-marker-acc)
1620	    gud-marker-acc ""))
1621
1622    output))
1623
1624(defcustom gud-pdb-command-name "pdb"
1625  "File name for executing the Python debugger.
1626This should be an executable on your path, or an absolute file name."
1627  :type 'string
1628  :group 'gud)
1629
1630;;;###autoload
1631(defun pdb (command-line)
1632  "Run pdb on program FILE in buffer `*gud-FILE*'.
1633The directory containing FILE becomes the initial working directory
1634and source-file directory for your debugger."
1635  (interactive
1636   (list (gud-query-cmdline 'pdb)))
1637
1638  (gud-common-init command-line nil 'gud-pdb-marker-filter)
1639  (set (make-local-variable 'gud-minor-mode) 'pdb)
1640
1641  (gud-def gud-break  "break %l"     "\C-b" "Set breakpoint at current line.")
1642  (gud-def gud-remove "clear %f:%l"  "\C-d" "Remove breakpoint at current line")
1643  (gud-def gud-step   "step"         "\C-s" "Step one source line with display.")
1644  (gud-def gud-next   "next"         "\C-n" "Step one line (skip functions).")
1645  (gud-def gud-cont   "continue"     "\C-r" "Continue with display.")
1646  (gud-def gud-finish "return"       "\C-f" "Finish executing current function.")
1647  (gud-def gud-up     "up"           "<" "Up one stack frame.")
1648  (gud-def gud-down   "down"         ">" "Down one stack frame.")
1649  (gud-def gud-print  "p %e"         "\C-p" "Evaluate Python expression at point.")
1650  ;; Is this right?
1651  (gud-def gud-statement "! %e"      "\C-e" "Execute Python statement at point.")
1652
1653  ;; (setq comint-prompt-regexp "^(.*pdb[+]?) *")
1654  (setq comint-prompt-regexp "^(Pdb) *")
1655  (setq paragraph-start comint-prompt-regexp)
1656  (run-hooks 'pdb-mode-hook))
1657
1658;; ======================================================================
1659;;
1660;; JDB support.
1661;;
1662;; AUTHOR:	Derek Davies <ddavies@world.std.com>
1663;;		Zoltan Kemenczy <zoltan@ieee.org;zkemenczy@rim.net>
1664;;
1665;; CREATED:	Sun Feb 22 10:46:38 1998 Derek Davies.
1666;; UPDATED:	Nov 11, 2001 Zoltan Kemenczy
1667;;              Dec 10, 2002 Zoltan Kemenczy - added nested class support
1668;;
1669;; INVOCATION NOTES:
1670;;
1671;; You invoke jdb-mode with:
1672;;
1673;;    M-x jdb <enter>
1674;;
1675;; It responds with:
1676;;
1677;;    Run jdb (like this): jdb
1678;;
1679;; type any jdb switches followed by the name of the class you'd like to debug.
1680;; Supply a fully qualfied classname (these do not have the ".class" extension)
1681;; for the name of the class to debug (e.g. "COM.the-kind.ddavies.CoolClass").
1682;; See the known problems section below for restrictions when specifying jdb
1683;; command line switches (search forward for '-classpath').
1684;;
1685;; You should see something like the following:
1686;;
1687;;    Current directory is ~/src/java/hello/
1688;;    Initializing jdb...
1689;;    0xed2f6628:class(hello)
1690;;    >
1691;;
1692;; To set an initial breakpoint try:
1693;;
1694;;    > stop in hello.main
1695;;    Breakpoint set in hello.main
1696;;    >
1697;;
1698;; To execute the program type:
1699;;
1700;;    > run
1701;;    run hello
1702;;
1703;;    Breakpoint hit: running ...
1704;;    hello.main (hello:12)
1705;;
1706;; Type M-n to step over the current line and M-s to step into it.  That,
1707;; along with the JDB 'help' command should get you started.  The 'quit'
1708;; JDB command will get out out of the debugger.  There is some truly
1709;; pathetic JDB documentation available at:
1710;;
1711;;     http://java.sun.com/products/jdk/1.1/debugging/
1712;;
1713;; KNOWN PROBLEMS AND FIXME's:
1714;;
1715;; Not sure what happens with inner classes ... haven't tried them.
1716;;
1717;; Does not grok UNICODE id's.  Only ASCII id's are supported.
1718;;
1719;; You must not put whitespace between "-classpath" and the path to
1720;; search for java classes even though it is required when invoking jdb
1721;; from the command line.  See gud-jdb-massage-args for details.
1722;; The same applies for "-sourcepath".
1723;;
1724;; Note: The following applies only if `gud-jdb-use-classpath' is nil;
1725;; refer to the documentation of `gud-jdb-use-classpath' and
1726;; `gud-jdb-classpath',`gud-jdb-sourcepath' variables for information
1727;; on using the classpath for locating java source files.
1728;;
1729;; If any of the source files in the directories listed in
1730;; gud-jdb-directories won't parse you'll have problems.  Make sure
1731;; every file ending in ".java" in these directories parses without error.
1732;;
1733;; All the .java files in the directories in gud-jdb-directories are
1734;; syntactically analyzed each time gud jdb is invoked.  It would be
1735;; nice to keep as much information as possible between runs.  It would
1736;; be really nice to analyze the files only as neccessary (when the
1737;; source needs to be displayed.)  I'm not sure to what extent the former
1738;; can be accomplished and I'm not sure the latter can be done at all
1739;; since I don't know of any general way to tell which .class files are
1740;; defined by which .java file without analyzing all the .java files.
1741;; If anyone knows why JavaSoft didn't put the source file names in
1742;; debuggable .class files please clue me in so I find something else
1743;; to be spiteful and bitter about.
1744;;
1745;; ======================================================================
1746;; gud jdb variables and functions
1747
1748(defcustom gud-jdb-command-name "jdb"
1749  "Command that executes the Java debugger."
1750  :type 'string
1751  :group 'gud)
1752
1753(defcustom gud-jdb-use-classpath t
1754  "If non-nil, search for Java source files in classpath directories.
1755The list of directories to search is the value of `gud-jdb-classpath'.
1756The file pathname is obtained by converting the fully qualified
1757class information output by jdb to a relative pathname and appending
1758it to `gud-jdb-classpath' element by element until a match is found.
1759
1760This method has a significant jdb startup time reduction advantage
1761since it does not require the scanning of all `gud-jdb-directories'
1762and parsing all Java files for class information.
1763
1764Set to nil to use `gud-jdb-directories' to scan java sources for
1765class information on jdb startup (original method)."
1766  :type 'boolean
1767  :group 'gud)
1768
1769(defvar gud-jdb-classpath nil
1770 "Java/jdb classpath directories list.
1771If `gud-jdb-use-classpath' is non-nil, gud-jdb derives the `gud-jdb-classpath'
1772list automatically using the following methods in sequence
1773\(with subsequent successful steps overriding the results of previous
1774steps):
1775
17761) Read the CLASSPATH environment variable,
17772) Read any \"-classpath\" argument used to run jdb,
1778   or detected in jdb output (e.g. if jdb is run by a script
1779   that echoes the actual jdb command before starting jdb)
17803) Send a \"classpath\" command to jdb and scan jdb output for
1781   classpath information if jdb is invoked with an \"-attach\" (to
1782   an already running VM) argument (This case typically does not
1783   have a \"-classpath\" command line argument - that is provided
1784   to the VM when it is started).
1785
1786Note that method 3 cannot be used with oldjdb (or Java 1 jdb) since
1787those debuggers do not support the classpath command. Use 1) or 2).")
1788
1789(defvar gud-jdb-sourcepath nil
1790  "Directory list provided by an (optional) \"-sourcepath\" option to jdb.
1791This list is prepended to `gud-jdb-classpath' to form the complete
1792list of directories searched for source files.")
1793
1794(defvar gud-marker-acc-max-length 4000
1795  "Maximum number of debugger output characters to keep.
1796This variable limits the size of `gud-marker-acc' which holds
1797the most recent debugger output history while searching for
1798source file information.")
1799
1800(defvar gud-jdb-history nil
1801"History of argument lists passed to jdb.")
1802
1803
1804;; List of Java source file directories.
1805(defvar gud-jdb-directories (list ".")
1806  "*A list of directories that gud jdb should search for source code.
1807The file names should be absolute, or relative to the current
1808directory.
1809
1810The set of .java files residing in the directories listed are
1811syntactically analyzed to determine the classes they define and the
1812packages in which these classes belong.  In this way gud jdb maps the
1813package-qualified class names output by the jdb debugger to the source
1814file from which the class originated.  This allows gud mode to keep
1815the source code display in sync with the debugging session.")
1816
1817(defvar gud-jdb-source-files nil
1818"List of the java source files for this debugging session.")
1819
1820;; Association list of fully qualified class names (package + class name)
1821;; and their source files.
1822(defvar gud-jdb-class-source-alist nil
1823"Association list of fully qualified class names and source files.")
1824
1825;; This is used to hold a source file during analysis.
1826(defvar gud-jdb-analysis-buffer nil)
1827
1828(defvar gud-jdb-classpath-string nil
1829"Holds temporary classpath values.")
1830
1831(defun gud-jdb-build-source-files-list (path extn)
1832"Return a list of java source files (absolute paths).
1833PATH gives the directories in which to search for files with
1834extension EXTN.  Normally EXTN is given as the regular expression
1835 \"\\.java$\" ."
1836  (apply 'nconc (mapcar (lambda (d)
1837			  (when (file-directory-p d)
1838			    (directory-files d t extn nil)))
1839			path)))
1840
1841;; Move point past whitespace.
1842(defun gud-jdb-skip-whitespace ()
1843  (skip-chars-forward " \n\r\t\014"))
1844
1845;; Move point past a "// <eol>" type of comment.
1846(defun gud-jdb-skip-single-line-comment ()
1847  (end-of-line))
1848
1849;; Move point past a "/* */" or "/** */" type of comment.
1850(defun gud-jdb-skip-traditional-or-documentation-comment ()
1851  (forward-char 2)
1852  (catch 'break
1853    (while (not (eobp))
1854      (if (eq (following-char) ?*)
1855	  (progn
1856	    (forward-char)
1857	    (if (not (eobp))
1858		(if (eq (following-char) ?/)
1859		    (progn
1860		      (forward-char)
1861		      (throw 'break nil)))))
1862	(forward-char)))))
1863
1864;; Move point past any number of consecutive whitespace chars and/or comments.
1865(defun gud-jdb-skip-whitespace-and-comments ()
1866  (gud-jdb-skip-whitespace)
1867  (catch 'done
1868    (while t
1869      (cond
1870       ((looking-at "//")
1871	(gud-jdb-skip-single-line-comment)
1872	(gud-jdb-skip-whitespace))
1873       ((looking-at "/\\*")
1874	(gud-jdb-skip-traditional-or-documentation-comment)
1875	(gud-jdb-skip-whitespace))
1876       (t (throw 'done nil))))))
1877
1878;; Move point past things that are id-like.  The intent is to skip regular
1879;; id's, such as class or interface names as well as package and interface
1880;; names.
1881(defun gud-jdb-skip-id-ish-thing ()
1882  (skip-chars-forward "^ /\n\r\t\014,;{"))
1883
1884;; Move point past a string literal.
1885(defun gud-jdb-skip-string-literal ()
1886  (forward-char)
1887  (while (not (cond
1888	       ((eq (following-char) ?\\)
1889		(forward-char))
1890	       ((eq (following-char) ?\042))))
1891    (forward-char))
1892  (forward-char))
1893
1894;; Move point past a character literal.
1895(defun gud-jdb-skip-character-literal ()
1896  (forward-char)
1897  (while
1898      (progn
1899	(if (eq (following-char) ?\\)
1900	    (forward-char 2))
1901	(not (eq (following-char) ?\')))
1902    (forward-char))
1903  (forward-char))
1904
1905;; Move point past the following block.  There may be (legal) cruft before
1906;; the block's opening brace.  There must be a block or it's the end of life
1907;; in petticoat junction.
1908(defun gud-jdb-skip-block ()
1909
1910  ;; Find the begining of the block.
1911  (while
1912      (not (eq (following-char) ?{))
1913
1914    ;; Skip any constructs that can harbor literal block delimiter
1915    ;; characters and/or the delimiters for the constructs themselves.
1916    (cond
1917     ((looking-at "//")
1918      (gud-jdb-skip-single-line-comment))
1919     ((looking-at "/\\*")
1920      (gud-jdb-skip-traditional-or-documentation-comment))
1921     ((eq (following-char) ?\042)
1922      (gud-jdb-skip-string-literal))
1923     ((eq (following-char) ?\')
1924      (gud-jdb-skip-character-literal))
1925     (t (forward-char))))
1926
1927  ;; Now at the begining of the block.
1928  (forward-char)
1929
1930  ;; Skip over the body of the block as well as the final brace.
1931  (let ((open-level 1))
1932    (while (not (eq open-level 0))
1933      (cond
1934       ((looking-at "//")
1935	(gud-jdb-skip-single-line-comment))
1936       ((looking-at "/\\*")
1937	(gud-jdb-skip-traditional-or-documentation-comment))
1938       ((eq (following-char) ?\042)
1939	(gud-jdb-skip-string-literal))
1940       ((eq (following-char) ?\')
1941	(gud-jdb-skip-character-literal))
1942       ((eq (following-char) ?{)
1943	(setq open-level (+ open-level 1))
1944	(forward-char))
1945       ((eq (following-char) ?})
1946	(setq open-level (- open-level 1))
1947	(forward-char))
1948       (t (forward-char))))))
1949
1950;; Find the package and class definitions in Java source file FILE.  Assumes
1951;; that FILE contains a legal Java program.  BUF is a scratch buffer used
1952;; to hold the source during analysis.
1953(defun gud-jdb-analyze-source (buf file)
1954  (let ((l nil))
1955    (set-buffer buf)
1956    (insert-file-contents file nil nil nil t)
1957    (goto-char 0)
1958    (catch 'abort
1959      (let ((p ""))
1960	(while (progn
1961		 (gud-jdb-skip-whitespace)
1962		 (not (eobp)))
1963	  (cond
1964
1965	   ;; Any number of semi's following a block is legal.  Move point
1966	   ;; past them.  Note that comments and whitespace may be
1967	   ;; interspersed as well.
1968	   ((eq (following-char) ?\073)
1969	    (forward-char))
1970
1971	   ;; Move point past a single line comment.
1972	   ((looking-at "//")
1973	    (gud-jdb-skip-single-line-comment))
1974
1975	   ;; Move point past a traditional or documentation comment.
1976	   ((looking-at "/\\*")
1977	    (gud-jdb-skip-traditional-or-documentation-comment))
1978
1979	   ;; Move point past a package statement, but save the PackageName.
1980	   ((looking-at "package")
1981	    (forward-char 7)
1982	    (gud-jdb-skip-whitespace-and-comments)
1983	    (let ((s (point)))
1984	      (gud-jdb-skip-id-ish-thing)
1985	      (setq p (concat (buffer-substring s (point)) "."))
1986	      (gud-jdb-skip-whitespace-and-comments)
1987	      (if (eq (following-char) ?\073)
1988		  (forward-char))))
1989
1990	   ;; Move point past an import statement.
1991	   ((looking-at "import")
1992	    (forward-char 6)
1993	    (gud-jdb-skip-whitespace-and-comments)
1994	    (gud-jdb-skip-id-ish-thing)
1995	    (gud-jdb-skip-whitespace-and-comments)
1996	    (if (eq (following-char) ?\073)
1997		(forward-char)))
1998
1999	   ;; Move point past the various kinds of ClassModifiers.
2000	   ((looking-at "public")
2001	    (forward-char 6))
2002	   ((looking-at "abstract")
2003	    (forward-char 8))
2004	   ((looking-at "final")
2005	    (forward-char 5))
2006
2007	   ;; Move point past a ClassDeclaraction, but save the class
2008	   ;; Identifier.
2009	   ((looking-at "class")
2010	    (forward-char 5)
2011	    (gud-jdb-skip-whitespace-and-comments)
2012	    (let ((s (point)))
2013	      (gud-jdb-skip-id-ish-thing)
2014	      (setq
2015	       l (nconc l (list (concat p (buffer-substring s (point)))))))
2016	    (gud-jdb-skip-block))
2017
2018	   ;; Move point past an interface statement.
2019	   ((looking-at "interface")
2020	    (forward-char 9)
2021	    (gud-jdb-skip-block))
2022
2023	   ;; Anything else means the input is invalid.
2024	   (t
2025	    (message "Error parsing file %s." file)
2026	    (throw 'abort nil))))))
2027    l))
2028
2029(defun gud-jdb-build-class-source-alist-for-file (file)
2030  (mapcar
2031   (lambda (c)
2032     (cons c file))
2033   (gud-jdb-analyze-source gud-jdb-analysis-buffer file)))
2034
2035;; Return an alist of fully qualified classes and the source files
2036;; holding their definitions.  SOURCES holds a list of all the source
2037;; files to examine.
2038(defun gud-jdb-build-class-source-alist (sources)
2039  (setq gud-jdb-analysis-buffer (get-buffer-create " *gud-jdb-scratch*"))
2040  (prog1
2041      (apply
2042       'nconc
2043       (mapcar
2044	'gud-jdb-build-class-source-alist-for-file
2045	sources))
2046    (kill-buffer gud-jdb-analysis-buffer)
2047    (setq gud-jdb-analysis-buffer nil)))
2048
2049;; Change what was given in the minibuffer to something that can be used to
2050;; invoke the debugger.
2051(defun gud-jdb-massage-args (file args)
2052  ;; The jdb executable must have whitespace between "-classpath" and
2053  ;; its value while gud-common-init expects all switch values to
2054  ;; follow the switch keyword without intervening whitespace.  We
2055  ;; require that when the user enters the "-classpath" switch in the
2056  ;; EMACS minibuffer that they do so without the intervening
2057  ;; whitespace.  This function adds it back (it's called after
2058  ;; gud-common-init).  There are more switches like this (for
2059  ;; instance "-host" and "-password") but I don't care about them
2060  ;; yet.
2061  (if args
2062      (let (massaged-args user-error)
2063
2064	(while (and args (not user-error))
2065	  (cond
2066	   ((setq user-error (string-match "-classpath$" (car args))))
2067	   ((setq user-error (string-match "-sourcepath$" (car args))))
2068	   ((string-match "-classpath\\(.+\\)" (car args))
2069	    (setq massaged-args
2070		  (append massaged-args
2071			  (list "-classpath"
2072				(setq gud-jdb-classpath-string
2073				      (match-string 1 (car args)))))))
2074	   ((string-match "-sourcepath\\(.+\\)" (car args))
2075	    (setq massaged-args
2076		  (append massaged-args
2077			  (list "-sourcepath"
2078				(setq gud-jdb-sourcepath
2079				      (match-string 1 (car args)))))))
2080	   (t (setq massaged-args (append massaged-args (list (car args))))))
2081	  (setq args (cdr args)))
2082
2083	;; By this point the current directory is all screwed up.  Maybe we
2084	;; could fix things and re-invoke gud-common-init, but for now I think
2085	;; issueing the error is good enough.
2086	(if user-error
2087	    (progn
2088	      (kill-buffer (current-buffer))
2089	      (error "Error: Omit whitespace between '-classpath or -sourcepath' and its value")))
2090	massaged-args)))
2091
2092;; Search for an association with P, a fully qualified class name, in
2093;; gud-jdb-class-source-alist.  The asssociation gives the fully
2094;; qualified file name of the source file which produced the class.
2095(defun gud-jdb-find-source-file (p)
2096  (cdr (assoc p gud-jdb-class-source-alist)))
2097
2098;; Note: Reset to this value every time a prompt is seen
2099(defvar gud-jdb-lowest-stack-level 999)
2100
2101(defun gud-jdb-find-source-using-classpath (p)
2102"Find source file corresponding to fully qualified class p.
2103Convert p from jdb's output, converted to a pathname
2104relative to a classpath directory."
2105  (save-match-data
2106    (let
2107      (;; Replace dots with slashes and append ".java" to generate file
2108       ;; name relative to classpath
2109       (filename
2110	(concat
2111	 (mapconcat 'identity
2112		    (split-string
2113		     ;; Eliminate any subclass references in the class
2114		     ;; name string. These start with a "$"
2115		     ((lambda (x)
2116			(if (string-match "$.*" x)
2117			    (replace-match "" t t x) p))
2118		      p)
2119		     "\\.") "/")
2120	 ".java"))
2121       (cplist (append gud-jdb-sourcepath gud-jdb-classpath))
2122       found-file)
2123    (while (and cplist
2124		(not (setq found-file
2125			   (file-readable-p
2126			    (concat (car cplist) "/" filename)))))
2127      (setq cplist (cdr cplist)))
2128    (if found-file (concat (car cplist) "/" filename)))))
2129
2130(defun gud-jdb-find-source (string)
2131"Alias for function used to locate source files.
2132Set to `gud-jdb-find-source-using-classpath' or `gud-jdb-find-source-file'
2133during jdb initialization depending on the value of
2134`gud-jdb-use-classpath'."
2135nil)
2136
2137(defun gud-jdb-parse-classpath-string (string)
2138"Parse the classpath list and convert each item to an absolute pathname."
2139  (mapcar (lambda (s) (if (string-match "[/\\]$" s)
2140			  (replace-match "" nil nil s) s))
2141	  (mapcar 'file-truename
2142		  (split-string
2143		   string
2144		   (concat "[ \t\n\r,\"" path-separator "]+")))))
2145
2146;; See comentary for other debugger's marker filters - there you will find
2147;; important notes about STRING.
2148(defun gud-jdb-marker-filter (string)
2149
2150  ;; Build up the accumulator.
2151  (setq gud-marker-acc
2152	(if gud-marker-acc
2153	    (concat gud-marker-acc string)
2154	  string))
2155
2156  ;; Look for classpath information until gud-jdb-classpath-string is found
2157  ;; (interactive, multiple settings of classpath from jdb
2158  ;;  not supported/followed)
2159  (if (and gud-jdb-use-classpath
2160	   (not gud-jdb-classpath-string)
2161	   (or (string-match "classpath:[ \t[]+\\([^]]+\\)" gud-marker-acc)
2162	       (string-match "-classpath[ \t\"]+\\([^ \"]+\\)" gud-marker-acc)))
2163      (setq gud-jdb-classpath
2164	    (gud-jdb-parse-classpath-string
2165	     (setq gud-jdb-classpath-string
2166		   (match-string 1 gud-marker-acc)))))
2167
2168  ;; We process STRING from left to right.  Each time through the
2169  ;; following loop we process at most one marker. After we've found a
2170  ;; marker, delete gud-marker-acc up to and including the match
2171  (let (file-found)
2172    ;; Process each complete marker in the input.
2173    (while
2174
2175	;; Do we see a marker?
2176	(string-match
2177	 ;; jdb puts out a string of the following form when it
2178	 ;; hits a breakpoint:
2179	 ;;
2180	 ;;	<fully-qualified-class><method> (<class>:<line-number>)
2181	 ;;
2182	 ;; <fully-qualified-class>'s are composed of Java ID's
2183	 ;; separated by periods.  <method> and <class> are
2184	 ;; also Java ID's.  <method> begins with a period and
2185	 ;; may contain less-than and greater-than (constructors,
2186	 ;; for instance, are called <init> in the symbol table.)
2187	 ;; Java ID's begin with a letter followed by letters
2188	 ;; and/or digits.  The set of letters includes underscore
2189	 ;; and dollar sign.
2190	 ;;
2191	 ;; The first group matches <fully-qualified-class>,
2192	 ;; the second group matches <class> and the third group
2193	 ;; matches <line-number>.  We don't care about using
2194	 ;; <method> so we don't "group" it.
2195	 ;;
2196	 ;; FIXME: Java ID's are UNICODE strings, this matches ASCII
2197	 ;; ID's only.
2198         ;;
2199         ;; The ".," in the last square-bracket are necessary because
2200         ;; of Sun's total disrespect for backwards compatibility in
2201         ;; reported line numbers from jdb - starting in 1.4.0 they
2202         ;; print line numbers using LOCALE, inserting a comma or a
2203         ;; period at the thousands positions (how ingenious!).
2204
2205	 "\\(\\[[0-9]+] \\)*\\([a-zA-Z0-9.$_]+\\)\\.[a-zA-Z0-9$_<>(),]+ \
2206\\(([a-zA-Z0-9.$_]+:\\|line=\\)\\([0-9.,]+\\)"
2207	 gud-marker-acc)
2208
2209      ;; A good marker is one that:
2210      ;; 1) does not have a "[n] " prefix (not part of a stack backtrace)
2211      ;; 2) does have an "[n] " prefix and n is the lowest prefix seen
2212      ;;    since the last prompt
2213      ;; Figure out the line on which to position the debugging arrow.
2214      ;; Return the info as a cons of the form:
2215      ;;
2216      ;;     (<file-name> . <line-number>) .
2217      (if (if (match-beginning 1)
2218	      (let (n)
2219		(setq n (string-to-number (substring
2220					gud-marker-acc
2221					(1+ (match-beginning 1))
2222					(- (match-end 1) 2))))
2223		(if (< n gud-jdb-lowest-stack-level)
2224		    (progn (setq gud-jdb-lowest-stack-level n) t)))
2225	    t)
2226	  (if (setq file-found
2227		    (gud-jdb-find-source (match-string 2 gud-marker-acc)))
2228	      (setq gud-last-frame
2229		    (cons file-found
2230			  (string-to-number
2231			   (let
2232                               ((numstr (match-string 4 gud-marker-acc)))
2233                             (if (string-match "[.,]" numstr)
2234                                 (replace-match "" nil nil numstr)
2235                               numstr)))))
2236	    (message "Could not find source file.")))
2237
2238      ;; Set the accumulator to the remaining text.
2239      (setq gud-marker-acc (substring gud-marker-acc (match-end 0))))
2240
2241    (if (string-match comint-prompt-regexp gud-marker-acc)
2242	(setq gud-jdb-lowest-stack-level 999)))
2243
2244  ;; Do not allow gud-marker-acc to grow without bound. If the source
2245  ;; file information is not within the last 3/4
2246  ;; gud-marker-acc-max-length characters, well,...
2247  (if (> (length gud-marker-acc) gud-marker-acc-max-length)
2248      (setq gud-marker-acc
2249	    (substring gud-marker-acc
2250		       (- (/ (* gud-marker-acc-max-length 3) 4)))))
2251
2252  ;; We don't filter any debugger output so just return what we were given.
2253  string)
2254
2255(defvar gud-jdb-command-name "jdb" "Command that executes the Java debugger.")
2256
2257;;;###autoload
2258(defun jdb (command-line)
2259  "Run jdb with command line COMMAND-LINE in a buffer.
2260The buffer is named \"*gud*\" if no initial class is given or
2261\"*gud-<initial-class-basename>*\" if there is.  If the \"-classpath\"
2262switch is given, omit all whitespace between it and its value.
2263
2264See `gud-jdb-use-classpath' and `gud-jdb-classpath' documentation for
2265information on how jdb accesses source files. Alternatively (if
2266`gud-jdb-use-classpath' is nil), see `gud-jdb-directories' for the
2267original source file access method.
2268
2269For general information about commands available to control jdb from
2270gud, see `gud-mode'."
2271  (interactive
2272   (list (gud-query-cmdline 'jdb)))
2273  (setq gud-jdb-classpath nil)
2274  (setq gud-jdb-sourcepath nil)
2275
2276  ;; Set gud-jdb-classpath from the CLASSPATH environment variable,
2277  ;; if CLASSPATH is set.
2278  (setq gud-jdb-classpath-string (getenv "CLASSPATH"))
2279  (if gud-jdb-classpath-string
2280      (setq gud-jdb-classpath
2281	    (gud-jdb-parse-classpath-string gud-jdb-classpath-string)))
2282  (setq gud-jdb-classpath-string nil)	; prepare for next
2283
2284  (gud-common-init command-line 'gud-jdb-massage-args
2285		   'gud-jdb-marker-filter)
2286  (set (make-local-variable 'gud-minor-mode) 'jdb)
2287
2288  ;; If a -classpath option was provided, set gud-jdb-classpath
2289  (if gud-jdb-classpath-string
2290      (setq gud-jdb-classpath
2291	    (gud-jdb-parse-classpath-string gud-jdb-classpath-string)))
2292  (setq gud-jdb-classpath-string nil)	; prepare for next
2293  ;; If a -sourcepath option was provided, parse it
2294  (if gud-jdb-sourcepath
2295      (setq gud-jdb-sourcepath
2296	    (gud-jdb-parse-classpath-string gud-jdb-sourcepath)))
2297
2298  (gud-def gud-break  "stop at %c:%l" "\C-b" "Set breakpoint at current line.")
2299  (gud-def gud-remove "clear %c:%l"   "\C-d" "Remove breakpoint at current line")
2300  (gud-def gud-step   "step"          "\C-s" "Step one source line with display.")
2301  (gud-def gud-next   "next"          "\C-n" "Step one line (skip functions).")
2302  (gud-def gud-cont   "cont"          "\C-r" "Continue with display.")
2303  (gud-def gud-finish "step up"       "\C-f" "Continue until current method returns.")
2304  (gud-def gud-up     "up\C-Mwhere"   "<"    "Up one stack frame.")
2305  (gud-def gud-down   "down\C-Mwhere" ">"    "Up one stack frame.")
2306  (gud-def gud-run    "run"           nil    "Run the program.") ;if VM start using jdb
2307  (gud-def gud-print  "print %e"  "\C-p" "Evaluate Java expression at point.")
2308
2309
2310  (setq comint-prompt-regexp "^> \\|^[^ ]+\\[[0-9]+\\] ")
2311  (setq paragraph-start comint-prompt-regexp)
2312  (run-hooks 'jdb-mode-hook)
2313
2314  (if gud-jdb-use-classpath
2315      ;; Get the classpath information from the debugger
2316      (progn
2317	(if (string-match "-attach" command-line)
2318	    (gud-call "classpath"))
2319	(fset 'gud-jdb-find-source
2320	      'gud-jdb-find-source-using-classpath))
2321
2322    ;; Else create and bind the class/source association list as well
2323    ;; as the source file list.
2324    (setq gud-jdb-class-source-alist
2325	  (gud-jdb-build-class-source-alist
2326	   (setq gud-jdb-source-files
2327		 (gud-jdb-build-source-files-list gud-jdb-directories
2328						  "\\.java$"))))
2329    (fset 'gud-jdb-find-source 'gud-jdb-find-source-file)))
2330
2331;;
2332;; End of debugger-specific information
2333;;
2334
2335
2336;; When we send a command to the debugger via gud-call, it's annoying
2337;; to see the command and the new prompt inserted into the debugger's
2338;; buffer; we have other ways of knowing the command has completed.
2339;;
2340;; If the buffer looks like this:
2341;; --------------------
2342;; (gdb) set args foo bar
2343;; (gdb) -!-
2344;; --------------------
2345;; (the -!- marks the location of point), and we type `C-x SPC' in a
2346;; source file to set a breakpoint, we want the buffer to end up like
2347;; this:
2348;; --------------------
2349;; (gdb) set args foo bar
2350;; Breakpoint 1 at 0x92: file make-docfile.c, line 49.
2351;; (gdb) -!-
2352;; --------------------
2353;; Essentially, the old prompt is deleted, and the command's output
2354;; and the new prompt take its place.
2355;;
2356;; Not echoing the command is easy enough; you send it directly using
2357;; process-send-string, and it never enters the buffer.  However,
2358;; getting rid of the old prompt is trickier; you don't want to do it
2359;; when you send the command, since that will result in an annoying
2360;; flicker as the prompt is deleted, redisplay occurs while Emacs
2361;; waits for a response from the debugger, and the new prompt is
2362;; inserted.  Instead, we'll wait until we actually get some output
2363;; from the subprocess before we delete the prompt.  If the command
2364;; produced no output other than a new prompt, that prompt will most
2365;; likely be in the first chunk of output received, so we will delete
2366;; the prompt and then replace it with an identical one.  If the
2367;; command produces output, the prompt is moving anyway, so the
2368;; flicker won't be annoying.
2369;;
2370;; So - when we want to delete the prompt upon receipt of the next
2371;; chunk of debugger output, we position gud-delete-prompt-marker at
2372;; the start of the prompt; the process filter will notice this, and
2373;; delete all text between it and the process output marker.  If
2374;; gud-delete-prompt-marker points nowhere, we leave the current
2375;; prompt alone.
2376(defvar gud-delete-prompt-marker nil)
2377
2378
2379(put 'gud-mode 'mode-class 'special)
2380
2381(define-derived-mode gud-mode comint-mode "Debugger"
2382  "Major mode for interacting with an inferior debugger process.
2383
2384   You start it up with one of the commands M-x gdb, M-x sdb, M-x dbx,
2385M-x perldb, M-x xdb, or M-x jdb.  Each entry point finishes by executing a
2386hook; `gdb-mode-hook', `sdb-mode-hook', `dbx-mode-hook',
2387`perldb-mode-hook', `xdb-mode-hook', or `jdb-mode-hook' respectively.
2388
2389After startup, the following commands are available in both the GUD
2390interaction buffer and any source buffer GUD visits due to a breakpoint stop
2391or step operation:
2392
2393\\[gud-break] sets a breakpoint at the current file and line.  In the
2394GUD buffer, the current file and line are those of the last breakpoint or
2395step.  In a source buffer, they are the buffer's file and current line.
2396
2397\\[gud-remove] removes breakpoints on the current file and line.
2398
2399\\[gud-refresh] displays in the source window the last line referred to
2400in the gud buffer.
2401
2402\\[gud-step], \\[gud-next], and \\[gud-stepi] do a step-one-line,
2403step-one-line (not entering function calls), and step-one-instruction
2404and then update the source window with the current file and position.
2405\\[gud-cont] continues execution.
2406
2407\\[gud-print] tries to find the largest C lvalue or function-call expression
2408around point, and sends it to the debugger for value display.
2409
2410The above commands are common to all supported debuggers except xdb which
2411does not support stepping instructions.
2412
2413Under gdb, sdb and xdb, \\[gud-tbreak] behaves exactly like \\[gud-break],
2414except that the breakpoint is temporary; that is, it is removed when
2415execution stops on it.
2416
2417Under gdb, dbx, and xdb, \\[gud-up] pops up through an enclosing stack
2418frame.  \\[gud-down] drops back down through one.
2419
2420If you are using gdb or xdb, \\[gud-finish] runs execution to the return from
2421the current function and stops.
2422
2423All the keystrokes above are accessible in the GUD buffer
2424with the prefix C-c, and in all buffers through the prefix C-x C-a.
2425
2426All pre-defined functions for which the concept make sense repeat
2427themselves the appropriate number of times if you give a prefix
2428argument.
2429
2430You may use the `gud-def' macro in the initialization hook to define other
2431commands.
2432
2433Other commands for interacting with the debugger process are inherited from
2434comint mode, which see."
2435  (setq mode-line-process '(":%s"))
2436  (define-key (current-local-map) "\C-c\C-l" 'gud-refresh)
2437  (set (make-local-variable 'gud-last-frame) nil)
2438  (set (make-local-variable 'tool-bar-map) gud-tool-bar-map)
2439  (make-local-variable 'comint-prompt-regexp)
2440  ;; Don't put repeated commands in command history many times.
2441  (set (make-local-variable 'comint-input-ignoredups) t)
2442  (make-local-variable 'paragraph-start)
2443  (set (make-local-variable 'gud-delete-prompt-marker) (make-marker))
2444  (add-hook 'kill-buffer-hook 'gud-kill-buffer-hook nil t))
2445
2446;; Cause our buffers to be displayed, by default,
2447;; in the selected window.
2448;;;###autoload (add-hook 'same-window-regexps "\\*gud-.*\\*\\(\\|<[0-9]+>\\)")
2449
2450(defcustom gud-chdir-before-run t
2451  "Non-nil if GUD should `cd' to the debugged executable."
2452  :group 'gud
2453  :type 'boolean)
2454
2455(defvar gud-target-name "--unknown--"
2456  "The apparent name of the program being debugged in a gud buffer.")
2457
2458;; Perform initializations common to all debuggers.
2459;; The first arg is the specified command line,
2460;; which starts with the program to debug.
2461;; The other three args specify the values to use
2462;; for local variables in the debugger buffer.
2463(defun gud-common-init (command-line massage-args marker-filter
2464				     &optional find-file)
2465  (let* ((words (split-string command-line))
2466	 (program (car words))
2467	 (dir default-directory)
2468	 ;; Extract the file name from WORDS
2469	 ;; and put t in its place.
2470	 ;; Later on we will put the modified file name arg back there.
2471	 (file-word (let ((w (cdr words)))
2472		      (while (and w (= ?- (aref (car w) 0)))
2473			(setq w (cdr w)))
2474		      (and w
2475			   (prog1 (car w)
2476			     (setcar w t)))))
2477	 (file-subst
2478	  (and file-word (substitute-in-file-name file-word)))
2479	 (args (cdr words))
2480	 ;; If a directory was specified, expand the file name.
2481	 ;; Otherwise, don't expand it, so GDB can use the PATH.
2482	 ;; A file name without directory is literally valid
2483	 ;; only if the file exists in ., and in that case,
2484	 ;; omitting the expansion here has no visible effect.
2485	 (file (and file-word
2486		    (if (file-name-directory file-subst)
2487			(expand-file-name file-subst)
2488		      file-subst)))
2489	 (filepart (and file-word (concat "-" (file-name-nondirectory file))))
2490	 (existing-buffer (get-buffer (concat "*gud" filepart "*"))))
2491    (pop-to-buffer (concat "*gud" filepart "*"))
2492    (when (and existing-buffer (get-buffer-process existing-buffer))
2493      (error "This program is already being debugged"))
2494    ;; Set the dir, in case the buffer already existed with a different dir.
2495    (setq default-directory dir)
2496    ;; Set default-directory to the file's directory.
2497    (and file-word
2498	 gud-chdir-before-run
2499	 ;; Don't set default-directory if no directory was specified.
2500	 ;; In that case, either the file is found in the current directory,
2501	 ;; in which case this setq is a no-op,
2502	 ;; or it is found by searching PATH,
2503	 ;; in which case we don't know what directory it was found in.
2504	 (file-name-directory file)
2505	 (setq default-directory (file-name-directory file)))
2506    (or (bolp) (newline))
2507    (insert "Current directory is " default-directory "\n")
2508    ;; Put the substituted and expanded file name back in its place.
2509    (let ((w args))
2510      (while (and w (not (eq (car w) t)))
2511	(setq w (cdr w)))
2512      (if w
2513	  (setcar w file)))
2514    (apply 'make-comint (concat "gud" filepart) program nil
2515	   (if massage-args (funcall massage-args file args) args))
2516    ;; Since comint clobbered the mode, we don't set it until now.
2517    (gud-mode)
2518    (set (make-local-variable 'gud-target-name)
2519	 (and file-word (file-name-nondirectory file))))
2520  (set (make-local-variable 'gud-marker-filter) marker-filter)
2521  (if find-file (set (make-local-variable 'gud-find-file) find-file))
2522  (setq gud-running nil)
2523  (setq gud-last-last-frame nil)
2524
2525  (set-process-filter (get-buffer-process (current-buffer)) 'gud-filter)
2526  (set-process-sentinel (get-buffer-process (current-buffer)) 'gud-sentinel)
2527  (gud-set-buffer))
2528
2529(defun gud-set-buffer ()
2530  (when (eq major-mode 'gud-mode)
2531    (setq gud-comint-buffer (current-buffer))))
2532
2533(defvar gud-filter-defer-flag nil
2534  "Non-nil means don't process anything from the debugger right now.
2535It is saved for when this flag is not set.")
2536
2537;; These functions are responsible for inserting output from your debugger
2538;; into the buffer.  The hard work is done by the method that is
2539;; the value of gud-marker-filter.
2540
2541(defun gud-filter (proc string)
2542  ;; Here's where the actual buffer insertion is done
2543  (let (output process-window)
2544    (if (buffer-name (process-buffer proc))
2545	(if gud-filter-defer-flag
2546	    ;; If we can't process any text now,
2547	    ;; save it for later.
2548	    (setq gud-filter-pending-text
2549		  (concat (or gud-filter-pending-text "") string))
2550
2551	  ;; If we have to ask a question during the processing,
2552	  ;; defer any additional text that comes from the debugger
2553	  ;; during that time.
2554	  (let ((gud-filter-defer-flag t))
2555	    ;; Process now any text we previously saved up.
2556	    (if gud-filter-pending-text
2557		(setq string (concat gud-filter-pending-text string)
2558		      gud-filter-pending-text nil))
2559
2560	    (with-current-buffer (process-buffer proc)
2561	      ;; If we have been so requested, delete the debugger prompt.
2562	      (save-restriction
2563		(widen)
2564		(if (marker-buffer gud-delete-prompt-marker)
2565		    (let ((inhibit-read-only t))
2566		      (delete-region (process-mark proc)
2567				     gud-delete-prompt-marker)
2568		      (comint-update-fence)
2569		      (set-marker gud-delete-prompt-marker nil)))
2570		;; Save the process output, checking for source file markers.
2571		(setq output (gud-marker-filter string))
2572		;; Check for a filename-and-line number.
2573		;; Don't display the specified file
2574		;; unless (1) point is at or after the position where output appears
2575		;; and (2) this buffer is on the screen.
2576		(setq process-window
2577		      (and gud-last-frame
2578			   (>= (point) (process-mark proc))
2579			   (get-buffer-window (current-buffer)))))
2580
2581	      ;; Let the comint filter do the actual insertion.
2582	      ;; That lets us inherit various comint features.
2583	      (comint-output-filter proc output))
2584
2585	    ;; Put the arrow on the source line.
2586	    ;; This must be outside of the save-excursion
2587	    ;; in case the source file is our current buffer.
2588	    (if process-window
2589		(with-selected-window process-window
2590		  (gud-display-frame))
2591	      ;; We have to be in the proper buffer, (process-buffer proc),
2592	      ;; but not in a save-excursion, because that would restore point.
2593	      (with-current-buffer (process-buffer proc)
2594		(gud-display-frame))))
2595
2596	  ;; If we deferred text that arrived during this processing,
2597	  ;; handle it now.
2598	  (if gud-filter-pending-text
2599	      (gud-filter proc ""))))))
2600
2601(defvar gud-minor-mode-type nil)
2602(defvar gud-overlay-arrow-position nil)
2603(add-to-list 'overlay-arrow-variable-list 'gud-overlay-arrow-position)
2604
2605(defun gud-sentinel (proc msg)
2606  (cond ((null (buffer-name (process-buffer proc)))
2607	 ;; buffer killed
2608	 ;; Stop displaying an arrow in a source file.
2609	 (setq gud-overlay-arrow-position nil)
2610	 (set-process-buffer proc nil)
2611	 (if (and (boundp 'speedbar-frame)
2612		  (string-equal speedbar-initial-expansion-list-name "GUD"))
2613	     (speedbar-change-initial-expansion-list
2614	      speedbar-previously-used-expansion-list-name))
2615	 (if (memq gud-minor-mode-type '(gdbmi gdba))
2616	     (gdb-reset)
2617	   (gud-reset)))
2618	((memq (process-status proc) '(signal exit))
2619	 ;; Stop displaying an arrow in a source file.
2620	 (setq gud-overlay-arrow-position nil)
2621	 (if (memq (buffer-local-value 'gud-minor-mode gud-comint-buffer)
2622		   '(gdba gdbmi))
2623	     (gdb-reset)
2624	   (gud-reset))
2625	 (let* ((obuf (current-buffer)))
2626	   ;; save-excursion isn't the right thing if
2627	   ;;  process-buffer is current-buffer
2628	   (unwind-protect
2629	       (progn
2630		 ;; Write something in *compilation* and hack its mode line,
2631		 (set-buffer (process-buffer proc))
2632		 ;; Fix the mode line.
2633		 (setq mode-line-process
2634		       (concat ":"
2635			       (symbol-name (process-status proc))))
2636		 (force-mode-line-update)
2637		 (if (eobp)
2638		     (insert ?\n mode-name " " msg)
2639		   (save-excursion
2640		     (goto-char (point-max))
2641		     (insert ?\n mode-name " " msg)))
2642		 ;; If buffer and mode line will show that the process
2643		 ;; is dead, we can delete it now.  Otherwise it
2644		 ;; will stay around until M-x list-processes.
2645		 (delete-process proc))
2646	     ;; Restore old buffer, but don't restore old point
2647	     ;; if obuf is the gud buffer.
2648	     (set-buffer obuf))))))
2649
2650(defun gud-kill-buffer-hook ()
2651  (setq gud-minor-mode-type gud-minor-mode)
2652  (condition-case nil
2653      (kill-process (get-buffer-process (current-buffer)))
2654    (error nil)))
2655
2656(defun gud-reset ()
2657  (dolist (buffer (buffer-list))
2658    (unless (eq buffer gud-comint-buffer)
2659      (with-current-buffer buffer
2660	(when gud-minor-mode
2661	  (setq gud-minor-mode nil)
2662	  (kill-local-variable 'tool-bar-map))))))
2663
2664(defun gud-display-frame ()
2665  "Find and obey the last filename-and-line marker from the debugger.
2666Obeying it means displaying in another window the specified file and line."
2667  (interactive)
2668  (when gud-last-frame
2669    (gud-set-buffer)
2670    (gud-display-line (car gud-last-frame) (cdr gud-last-frame))
2671    (setq gud-last-last-frame gud-last-frame
2672	  gud-last-frame nil)))
2673
2674;; Make sure the file named TRUE-FILE is in a buffer that appears on the screen
2675;; and that its line LINE is visible.
2676;; Put the overlay-arrow on the line LINE in that buffer.
2677;; Most of the trickiness in here comes from wanting to preserve the current
2678;; region-restriction if that's possible.  We use an explicit display-buffer
2679;; to get around the fact that this is called inside a save-excursion.
2680
2681(defun gud-display-line (true-file line)
2682  (let* ((last-nonmenu-event t)	 ; Prevent use of dialog box for questions.
2683	 (buffer
2684	  (with-current-buffer gud-comint-buffer
2685	    (gud-find-file true-file)))
2686	 (window (and buffer (or (get-buffer-window buffer)
2687				 (if (memq gud-minor-mode '(gdbmi gdba))
2688				     (unless (gdb-display-source-buffer buffer)
2689				       (gdb-display-buffer buffer nil)))
2690				 (display-buffer buffer))))
2691	 (pos))
2692    (if buffer
2693	(progn
2694	  (with-current-buffer buffer
2695	    (unless (or (verify-visited-file-modtime buffer) gud-keep-buffer)
2696		  (if (yes-or-no-p
2697		       (format "File %s changed on disk.  Reread from disk? "
2698			       (buffer-name)))
2699		      (revert-buffer t t)
2700		    (setq gud-keep-buffer t)))
2701	    (save-restriction
2702	      (widen)
2703	      (goto-line line)
2704	      (setq pos (point))
2705	      (or gud-overlay-arrow-position
2706		  (setq gud-overlay-arrow-position (make-marker)))
2707	      (set-marker gud-overlay-arrow-position (point) (current-buffer))
2708	      ;; If they turned on hl-line, move the hl-line highlight to
2709	      ;; the arrow's line.
2710	      (when (featurep 'hl-line)
2711		(cond
2712		 (global-hl-line-mode
2713		  (global-hl-line-highlight))
2714		 ((and hl-line-mode hl-line-sticky-flag)
2715		  (hl-line-highlight)))))
2716	    (cond ((or (< pos (point-min)) (> pos (point-max)))
2717		   (widen)
2718		   (goto-char pos))))
2719	  (when window
2720	    (set-window-point window gud-overlay-arrow-position)
2721	    (if (memq gud-minor-mode '(gdbmi gdba))
2722		(setq gdb-source-window window)))))))
2723
2724;; The gud-call function must do the right thing whether its invoking
2725;; keystroke is from the GUD buffer itself (via major-mode binding)
2726;; or a C buffer.  In the former case, we want to supply data from
2727;; gud-last-frame.  Here's how we do it:
2728
2729(defun gud-format-command (str arg)
2730  (let ((insource (not (eq (current-buffer) gud-comint-buffer)))
2731	(frame (or gud-last-frame gud-last-last-frame))
2732	result)
2733    (while (and str
2734		(let ((case-fold-search nil))
2735		  (string-match "\\([^%]*\\)%\\([adefFlpc]\\)" str)))
2736      (let ((key (string-to-char (match-string 2 str)))
2737	    subst)
2738	(cond
2739	 ((eq key ?f)
2740	  (setq subst (file-name-nondirectory (if insource
2741						  (buffer-file-name)
2742						(car frame)))))
2743	 ((eq key ?F)
2744	  (setq subst (file-name-sans-extension
2745		       (file-name-nondirectory (if insource
2746						   (buffer-file-name)
2747						 (car frame))))))
2748	 ((eq key ?d)
2749	  (setq subst (file-name-directory (if insource
2750					       (buffer-file-name)
2751					     (car frame)))))
2752	 ((eq key ?l)
2753	  (setq subst (int-to-string
2754		       (if insource
2755			   (save-restriction
2756			     (widen)
2757			     (+ (count-lines (point-min) (point))
2758				(if (bolp) 1 0)))
2759			 (cdr frame)))))
2760	 ((eq key ?e)
2761	  (setq subst (gud-find-expr)))
2762	 ((eq key ?a)
2763	  (setq subst (gud-read-address)))
2764	 ((eq key ?c)
2765	  (setq subst
2766                (gud-find-class
2767                 (if insource
2768                      (buffer-file-name)
2769                    (car frame))
2770                 (if insource
2771                      (save-restriction
2772                        (widen)
2773                        (+ (count-lines (point-min) (point))
2774                           (if (bolp) 1 0)))
2775                    (cdr frame)))))
2776	 ((eq key ?p)
2777	  (setq subst (if arg (int-to-string arg)))))
2778	(setq result (concat result (match-string 1 str) subst)))
2779      (setq str (substring str (match-end 2))))
2780    ;; There might be text left in STR when the loop ends.
2781    (concat result str)))
2782
2783(defun gud-read-address ()
2784  "Return a string containing the core-address found in the buffer at point."
2785  (save-match-data
2786    (save-excursion
2787      (let ((pt (point)) found begin)
2788	(setq found (if (search-backward "0x" (- pt 7) t) (point)))
2789	(cond
2790	 (found (forward-char 2)
2791		(buffer-substring found
2792				  (progn (re-search-forward "[^0-9a-f]")
2793					 (forward-char -1)
2794					 (point))))
2795	 (t (setq begin (progn (re-search-backward "[^0-9]")
2796			       (forward-char 1)
2797			       (point)))
2798	    (forward-char 1)
2799	    (re-search-forward "[^0-9]")
2800	    (forward-char -1)
2801	    (buffer-substring begin (point))))))))
2802
2803(defun gud-call (fmt &optional arg)
2804  (let ((msg (gud-format-command fmt arg)))
2805    (message "Command: %s" msg)
2806    (sit-for 0)
2807    (gud-basic-call msg)))
2808
2809(defun gud-basic-call (command)
2810  "Invoke the debugger COMMAND displaying source in other window."
2811  (interactive)
2812  (gud-set-buffer)
2813  (let ((proc (get-buffer-process gud-comint-buffer)))
2814    (or proc (error "Current buffer has no process"))
2815    ;; Arrange for the current prompt to get deleted.
2816    (save-excursion
2817      (set-buffer gud-comint-buffer)
2818      (save-restriction
2819	(widen)
2820	(if (marker-position gud-delete-prompt-marker)
2821	    ;; We get here when printing an expression.
2822	    (goto-char gud-delete-prompt-marker)
2823	  (goto-char (process-mark proc))
2824	  (forward-line 0))
2825	(if (looking-at comint-prompt-regexp)
2826	    (set-marker gud-delete-prompt-marker (point)))
2827	(if (memq gud-minor-mode '(gdbmi gdba))
2828	    (apply comint-input-sender (list proc command))
2829	  (process-send-string proc (concat command "\n")))))))
2830
2831(defun gud-refresh (&optional arg)
2832  "Fix up a possibly garbled display, and redraw the arrow."
2833  (interactive "P")
2834  (or gud-last-frame (setq gud-last-frame gud-last-last-frame))
2835  (gud-display-frame)
2836  (recenter arg))
2837
2838;; Code for parsing expressions out of C or Fortran code.  The single entry
2839;; point is gud-find-expr, which tries to return an lvalue expression from
2840;; around point.
2841
2842(defvar gud-find-expr-function 'gud-find-c-expr)
2843
2844(defun gud-find-expr (&rest args)
2845  (let ((expr (if (and transient-mark-mode mark-active)
2846		  (buffer-substring (region-beginning) (region-end))
2847		(apply gud-find-expr-function args))))
2848    (save-match-data
2849      (if (string-match "\n" expr)
2850	  (error "Expression must not include a newline"))
2851      (with-current-buffer gud-comint-buffer
2852	(save-excursion
2853	  (goto-char (process-mark (get-buffer-process gud-comint-buffer)))
2854	  (forward-line 0)
2855	  (when (looking-at comint-prompt-regexp)
2856	    (set-marker gud-delete-prompt-marker (point))
2857	    (set-marker-insertion-type gud-delete-prompt-marker t))
2858	  (unless (eq (buffer-local-value 'gud-minor-mode gud-comint-buffer)
2859		      'jdb)
2860	      (insert (concat  expr " = "))))))
2861    expr))
2862
2863;; The next eight functions are hacked from gdbsrc.el by
2864;; Debby Ayers <ayers@asc.slb.com>,
2865;; Rich Schaefer <schaefer@asc.slb.com> Schlumberger, Austin, Tx.
2866
2867(defun gud-find-c-expr ()
2868  "Returns the expr that surrounds point."
2869  (interactive)
2870  (save-excursion
2871    (let ((p (point))
2872	  (expr (gud-innermost-expr))
2873	  (test-expr (gud-prev-expr)))
2874      (while (and test-expr (gud-expr-compound test-expr expr))
2875	(let ((prev-expr expr))
2876	  (setq expr (cons (car test-expr) (cdr expr)))
2877	  (goto-char (car expr))
2878	  (setq test-expr (gud-prev-expr))
2879	  ;; If we just pasted on the condition of an if or while,
2880	  ;; throw it away again.
2881	  (if (member (buffer-substring (car test-expr) (cdr test-expr))
2882		      '("if" "while" "for"))
2883	      (setq test-expr nil
2884		    expr prev-expr))))
2885      (goto-char p)
2886      (setq test-expr (gud-next-expr))
2887      (while (gud-expr-compound expr test-expr)
2888	(setq expr (cons (car expr) (cdr test-expr)))
2889	(setq test-expr (gud-next-expr)))
2890      (buffer-substring (car expr) (cdr expr)))))
2891
2892(defun gud-innermost-expr ()
2893  "Returns the smallest expr that point is in; move point to beginning of it.
2894The expr is represented as a cons cell, where the car specifies the point in
2895the current buffer that marks the beginning of the expr and the cdr specifies
2896the character after the end of the expr."
2897  (let ((p (point)) begin end)
2898    (gud-backward-sexp)
2899    (setq begin (point))
2900    (gud-forward-sexp)
2901    (setq end (point))
2902    (if (>= p end)
2903	(progn
2904	 (setq begin p)
2905	 (goto-char p)
2906	 (gud-forward-sexp)
2907	 (setq end (point)))
2908      )
2909    (goto-char begin)
2910    (cons begin end)))
2911
2912(defun gud-backward-sexp ()
2913  "Version of `backward-sexp' that catches errors."
2914  (condition-case nil
2915      (backward-sexp)
2916    (error t)))
2917
2918(defun gud-forward-sexp ()
2919  "Version of `forward-sexp' that catches errors."
2920  (condition-case nil
2921     (forward-sexp)
2922    (error t)))
2923
2924(defun gud-prev-expr ()
2925  "Returns the previous expr, point is set to beginning of that expr.
2926The expr is represented as a cons cell, where the car specifies the point in
2927the current buffer that marks the beginning of the expr and the cdr specifies
2928the character after the end of the expr"
2929  (let ((begin) (end))
2930    (gud-backward-sexp)
2931    (setq begin (point))
2932    (gud-forward-sexp)
2933    (setq end (point))
2934    (goto-char begin)
2935    (cons begin end)))
2936
2937(defun gud-next-expr ()
2938  "Returns the following expr, point is set to beginning of that expr.
2939The expr is represented as a cons cell, where the car specifies the point in
2940the current buffer that marks the beginning of the expr and the cdr specifies
2941the character after the end of the expr."
2942  (let ((begin) (end))
2943    (gud-forward-sexp)
2944    (gud-forward-sexp)
2945    (setq end (point))
2946    (gud-backward-sexp)
2947    (setq begin (point))
2948    (cons begin end)))
2949
2950(defun gud-expr-compound-sep (span-start span-end)
2951  "Scan from SPAN-START to SPAN-END for punctuation characters.
2952If `->' is found, return `?.'.  If `.' is found, return `?.'.
2953If any other punctuation is found, return `??'.
2954If no punctuation is found, return `? '."
2955  (let ((result ?\s)
2956	(syntax))
2957    (while (< span-start span-end)
2958      (setq syntax (char-syntax (char-after span-start)))
2959      (cond
2960       ((= syntax ?\s) t)
2961       ((= syntax ?.) (setq syntax (char-after span-start))
2962	(cond
2963	 ((= syntax ?.) (setq result ?.))
2964	 ((and (= syntax ?-) (= (char-after (+ span-start 1)) ?>))
2965	  (setq result ?.)
2966	  (setq span-start (+ span-start 1)))
2967	 (t (setq span-start span-end)
2968	    (setq result ??)))))
2969      (setq span-start (+ span-start 1)))
2970    result))
2971
2972(defun gud-expr-compound (first second)
2973  "Non-nil if concatenating FIRST and SECOND makes a single C expression.
2974The two exprs are represented as a cons cells, where the car
2975specifies the point in the current buffer that marks the beginning of the
2976expr and the cdr specifies the character after the end of the expr.
2977Link exprs of the form:
2978      Expr -> Expr
2979      Expr . Expr
2980      Expr (Expr)
2981      Expr [Expr]
2982      (Expr) Expr
2983      [Expr] Expr"
2984  (let ((span-start (cdr first))
2985	(span-end (car second))
2986	(syntax))
2987    (setq syntax (gud-expr-compound-sep span-start span-end))
2988    (cond
2989     ((= (car first) (car second)) nil)
2990     ((= (cdr first) (cdr second)) nil)
2991     ((= syntax ?.) t)
2992     ((= syntax ?\s)
2993      (setq span-start (char-after (- span-start 1)))
2994      (setq span-end (char-after span-end))
2995      (cond
2996       ((= span-start ?)) t)
2997      ((= span-start ?]) t)
2998     ((= span-end ?() t)
2999      ((= span-end ?[) t)
3000       (t nil)))
3001     (t nil))))
3002
3003(defun gud-find-class (f line)
3004  "Find fully qualified class in file F at line LINE.
3005This function uses the `gud-jdb-classpath' (and optional
3006`gud-jdb-sourcepath') list(s) to derive a file
3007pathname relative to its classpath directory. The values in
3008`gud-jdb-classpath' are assumed to have been converted to absolute
3009pathname standards using file-truename.
3010If F is visited by a buffer and its mode is CC-mode(Java),
3011syntactic information of LINE is used to find the enclosing (nested)
3012class string which is appended to the top level
3013class of the file (using s to separate nested class ids)."
3014  ;; Convert f to a standard representation and remove suffix
3015  (if (and gud-jdb-use-classpath (or gud-jdb-classpath gud-jdb-sourcepath))
3016      (save-match-data
3017        (let ((cplist (append gud-jdb-sourcepath gud-jdb-classpath))
3018              (fbuffer (get-file-buffer f))
3019              syntax-symbol syntax-point class-found)
3020          (setq f (file-name-sans-extension (file-truename f)))
3021          ;; Syntax-symbol returns the symbol of the *first* element
3022          ;; in the syntactical analysis result list, syntax-point
3023          ;; returns the buffer position of same
3024          (fset 'syntax-symbol (lambda (x) (c-langelem-sym (car x))))
3025          (fset 'syntax-point (lambda (x) (c-langelem-pos (car x))))
3026          ;; Search through classpath list for an entry that is
3027          ;; contained in f
3028          (while (and cplist (not class-found))
3029            (if (string-match (car cplist) f)
3030                (setq class-found
3031		      (mapconcat 'identity
3032                                 (split-string
3033                                   (substring f (+ (match-end 0) 1))
3034                                  "/") ".")))
3035            (setq cplist (cdr cplist)))
3036          ;; if f is visited by a java(cc-mode) buffer, walk up the
3037          ;; syntactic information chain and collect any 'inclass
3038          ;; symbols until 'topmost-intro is reached to find out if
3039          ;; point is within a nested class
3040          (if (and fbuffer (equal (symbol-file 'java-mode) "cc-mode"))
3041              (save-excursion
3042                (set-buffer fbuffer)
3043                (let ((nclass) (syntax))
3044                  ;; While the c-syntactic information does not start
3045                  ;; with the 'topmost-intro symbol, there may be
3046                  ;; nested classes...
3047                  (while (not (eq 'topmost-intro
3048                                  (syntax-symbol (c-guess-basic-syntax))))
3049                    ;; Check if the current position c-syntactic
3050                    ;; analysis has 'inclass
3051                    (setq syntax (c-guess-basic-syntax))
3052                    (while
3053                        (and (not (eq 'inclass (syntax-symbol syntax)))
3054                             (cdr syntax))
3055                      (setq syntax (cdr syntax)))
3056                    (if (eq 'inclass (syntax-symbol syntax))
3057                        (progn
3058                          (goto-char (syntax-point syntax))
3059                          ;; Now we're at the beginning of a class
3060                          ;; definition.  Find class name
3061                          (looking-at
3062                           "[A-Za-z0-9 \t\n]*?class[ \t\n]+\\([^ \t\n]+\\)")
3063                          (setq nclass
3064                                (append (list (match-string-no-properties 1))
3065                                        nclass)))
3066                      (setq syntax (c-guess-basic-syntax))
3067                      (while (and (not (syntax-point syntax)) (cdr syntax))
3068                        (setq syntax (cdr syntax)))
3069                      (goto-char (syntax-point syntax))
3070                      ))
3071                  (string-match (concat (car nclass) "$") class-found)
3072                  (setq class-found
3073                        (replace-match (mapconcat 'identity nclass "$")
3074                                       t t class-found)))))
3075          (if (not class-found)
3076              (message "gud-find-class: class for file %s not found!" f))
3077          class-found))
3078    ;; Not using classpath - try class/source association list
3079    (let ((class-found (rassoc f gud-jdb-class-source-alist)))
3080      (if class-found
3081	  (car class-found)
3082	(message "gud-find-class: class for file %s not found in gud-jdb-class-source-alist!" f)
3083	nil))))
3084
3085
3086;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3087;;; GDB script mode ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3088;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3089
3090(defvar gdb-script-mode-syntax-table
3091  (let ((st (make-syntax-table)))
3092    (modify-syntax-entry ?' "\"" st)
3093    (modify-syntax-entry ?# "<" st)
3094    (modify-syntax-entry ?\n ">" st)
3095    st))
3096
3097(defvar gdb-script-font-lock-keywords
3098  '(("^define\\s-+\\(\\(\\w\\|\\s_\\)+\\)" (1 font-lock-function-name-face))
3099    ("\\$\\(\\w+\\)" (1 font-lock-variable-name-face))
3100    ("^\\s-*\\(\\w\\(\\w\\|\\s_\\)*\\)" (1 font-lock-keyword-face))))
3101
3102(defvar gdb-script-font-lock-syntactic-keywords
3103  '(("^document\\s-.*\\(\n\\)" (1 "< b"))
3104    ("^end\\>"
3105     (0 (unless (eq (match-beginning 0) (point-min))
3106          ;; We change the \n in front, which is more difficult, but results
3107          ;; in better highlighting.  If the doc is empty, the single \n is
3108          ;; both the beginning and the end of the docstring, which can't be
3109          ;; expressed in syntax-tables.  Instead, we place the "> b" after
3110          ;; placing the "< b", so the start marker is overwritten by the
3111          ;; termination marker and in the end Emacs simply considers that
3112          ;; there's no docstring at all, which is fine.
3113          (put-text-property (1- (match-beginning 0)) (match-beginning 0)
3114                             'syntax-table (eval-when-compile
3115                                             (string-to-syntax "> b")))
3116          ;; Make sure that rehighlighting the previous line won't erase our
3117          ;; syntax-table property.
3118          (put-text-property (1- (match-beginning 0)) (match-end 0)
3119                             'font-lock-multiline t)
3120          nil)))))
3121
3122(defun gdb-script-font-lock-syntactic-face (state)
3123  (cond
3124   ((nth 3 state) font-lock-string-face)
3125   ((nth 7 state) font-lock-doc-face)
3126   (t font-lock-comment-face)))
3127
3128(defvar gdb-script-basic-indent 2)
3129
3130(defun gdb-script-skip-to-head ()
3131  "We're just in front of an `end' and we need to go to its head."
3132  (while (and (re-search-backward "^\\s-*\\(\\(end\\)\\|define\\|document\\|if\\|while\\|commands\\)\\>" nil 'move)
3133	      (match-end 2))
3134    (gdb-script-skip-to-head)))
3135
3136(defun gdb-script-calculate-indentation ()
3137  (cond
3138   ((looking-at "end\\>")
3139    (gdb-script-skip-to-head)
3140    (current-indentation))
3141   ((looking-at "else\\>")
3142    (while (and (re-search-backward "^\\s-*\\(if\\|\\(end\\)\\)\\>" nil 'move)
3143		(match-end 2))
3144      (gdb-script-skip-to-head))
3145    (current-indentation))
3146   (t
3147    (forward-comment (- (point-max)))
3148    (forward-line 0)
3149    (skip-chars-forward " \t")
3150    (+ (current-indentation)
3151       (if (looking-at "\\(if\\|while\\|define\\|else\\|commands\\)\\>")
3152	   gdb-script-basic-indent 0)))))
3153
3154(defun gdb-script-indent-line ()
3155  "Indent current line of GDB script."
3156  (interactive)
3157  (if (and (eq (get-text-property (point) 'face) font-lock-doc-face)
3158	   (save-excursion
3159	     (forward-line 0)
3160	     (skip-chars-forward " \t")
3161	     (not (looking-at "end\\>"))))
3162      'noindent
3163    (let* ((savep (point))
3164	   (indent (condition-case nil
3165		       (save-excursion
3166			 (forward-line 0)
3167			 (skip-chars-forward " \t")
3168			 (if (>= (point) savep) (setq savep nil))
3169			 (max (gdb-script-calculate-indentation) 0))
3170		     (error 0))))
3171      (if savep
3172	  (save-excursion (indent-line-to indent))
3173	(indent-line-to indent)))))
3174
3175;; Derived from cfengine.el.
3176(defun gdb-script-beginning-of-defun ()
3177  "`beginning-of-defun' function for Gdb script mode.
3178Treats actions as defuns."
3179  (unless (<= (current-column) (current-indentation))
3180    (end-of-line))
3181  (if (re-search-backward "^define \\|^document " nil t)
3182      (beginning-of-line)
3183    (goto-char (point-min)))
3184  t)
3185
3186;; Derived from cfengine.el.
3187(defun gdb-script-end-of-defun ()
3188  "`end-of-defun' function for Gdb script mode.
3189Treats actions as defuns."
3190  (end-of-line)
3191  (if (re-search-forward "^end" nil t)
3192      (beginning-of-line)
3193    (goto-char (point-max)))
3194  t)
3195
3196;;;###autoload
3197(add-to-list 'auto-mode-alist '("/\\.gdbinit" . gdb-script-mode))
3198
3199;;;###autoload
3200(define-derived-mode gdb-script-mode nil "GDB-Script"
3201  "Major mode for editing GDB scripts"
3202  (set (make-local-variable 'comment-start) "#")
3203  (set (make-local-variable 'comment-start-skip) "#+\\s-*")
3204  (set (make-local-variable 'outline-regexp) "[ \t]")
3205  (set (make-local-variable 'imenu-generic-expression)
3206       '((nil "^define[ \t]+\\(\\w+\\)" 1)))
3207  (set (make-local-variable 'indent-line-function) 'gdb-script-indent-line)
3208  (set (make-local-variable 'beginning-of-defun-function)
3209       #'gdb-script-beginning-of-defun)
3210  (set (make-local-variable 'end-of-defun-function)
3211       #'gdb-script-end-of-defun)
3212  (set (make-local-variable 'font-lock-defaults)
3213       '(gdb-script-font-lock-keywords nil nil ((?_ . "w")) nil
3214	 (font-lock-syntactic-keywords
3215	  . gdb-script-font-lock-syntactic-keywords)
3216	 (font-lock-syntactic-face-function
3217	  . gdb-script-font-lock-syntactic-face))))
3218
3219
3220;;; tooltips for GUD
3221
3222;;; Customizable settings
3223
3224(define-minor-mode gud-tooltip-mode
3225  "Toggle the display of GUD tooltips."
3226  :global t
3227  :group 'gud
3228  :group 'tooltip
3229  (require 'tooltip)
3230  (if gud-tooltip-mode
3231      (progn
3232	(add-hook 'change-major-mode-hook 'gud-tooltip-change-major-mode)
3233	(add-hook 'pre-command-hook 'tooltip-hide)
3234	(add-hook 'tooltip-hook 'gud-tooltip-tips)
3235	(define-key global-map [mouse-movement] 'gud-tooltip-mouse-motion))
3236    (unless tooltip-mode (remove-hook 'pre-command-hook 'tooltip-hide)
3237    (remove-hook 'change-major-mode-hook 'gud-tooltip-change-major-mode)
3238    (remove-hook 'tooltip-hook 'gud-tooltip-tips)
3239    (define-key global-map [mouse-movement] 'ignore)))
3240  (gud-tooltip-activate-mouse-motions-if-enabled)
3241  (if (and gud-comint-buffer
3242	   (buffer-name gud-comint-buffer); gud-comint-buffer might be killed
3243	   (memq (buffer-local-value 'gud-minor-mode gud-comint-buffer)
3244		 '(gdbmi gdba)))
3245      (if gud-tooltip-mode
3246	  (progn
3247	    (dolist (buffer (buffer-list))
3248	      (unless (eq buffer gud-comint-buffer)
3249		(with-current-buffer buffer
3250		  (when (and (memq gud-minor-mode '(gdbmi gdba))
3251			     (not (string-match "\\`\\*.+\\*\\'"
3252						(buffer-name))))
3253		    (make-local-variable 'gdb-define-alist)
3254		    (gdb-create-define-alist)
3255		    (add-hook 'after-save-hook
3256			      'gdb-create-define-alist nil t))))))
3257	(kill-local-variable 'gdb-define-alist)
3258	(remove-hook 'after-save-hook 'gdb-create-define-alist t))))
3259
3260(defcustom gud-tooltip-modes '(gud-mode c-mode c++-mode fortran-mode
3261					python-mode)
3262  "List of modes for which to enable GUD tooltips."
3263  :type 'sexp
3264  :group 'gud
3265  :group 'tooltip)
3266
3267(defcustom gud-tooltip-display
3268  '((eq (tooltip-event-buffer gud-tooltip-event)
3269	(marker-buffer gud-overlay-arrow-position)))
3270  "List of forms determining where GUD tooltips are displayed.
3271
3272Forms in the list are combined with AND.  The default is to display
3273only tooltips in the buffer containing the overlay arrow."
3274  :type 'sexp
3275  :group 'gud
3276  :group 'tooltip)
3277
3278(defcustom gud-tooltip-echo-area nil
3279  "Use the echo area instead of frames for GUD tooltips."
3280  :type 'boolean
3281  :group 'gud
3282  :group 'tooltip)
3283
3284(define-obsolete-variable-alias 'tooltip-gud-modes
3285                                'gud-tooltip-modes "22.1")
3286(define-obsolete-variable-alias 'tooltip-gud-display
3287                                'gud-tooltip-display "22.1")
3288
3289;;; Reacting on mouse movements
3290
3291(defun gud-tooltip-change-major-mode ()
3292  "Function added to `change-major-mode-hook' when tooltip mode is on."
3293  (add-hook 'post-command-hook 'gud-tooltip-activate-mouse-motions-if-enabled))
3294
3295(defun gud-tooltip-activate-mouse-motions-if-enabled ()
3296  "Reconsider for all buffers whether mouse motion events are desired."
3297  (remove-hook 'post-command-hook
3298	       'gud-tooltip-activate-mouse-motions-if-enabled)
3299  (dolist (buffer (buffer-list))
3300    (save-excursion
3301      (set-buffer buffer)
3302      (if (and gud-tooltip-mode
3303	       (memq major-mode gud-tooltip-modes))
3304	  (gud-tooltip-activate-mouse-motions t)
3305	(gud-tooltip-activate-mouse-motions nil)))))
3306
3307(defvar gud-tooltip-mouse-motions-active nil
3308  "Locally t in a buffer if tooltip processing of mouse motion is enabled.")
3309
3310;; We don't set track-mouse globally because this is a big redisplay
3311;; problem in buffers having a pre-command-hook or such installed,
3312;; which does a set-buffer, like the summary buffer of Gnus.  Calling
3313;; set-buffer prevents redisplay optimizations, so every mouse motion
3314;; would be accompanied by a full redisplay.
3315
3316(defun gud-tooltip-activate-mouse-motions (activatep)
3317  "Activate/deactivate mouse motion events for the current buffer.
3318ACTIVATEP non-nil means activate mouse motion events."
3319  (if activatep
3320      (progn
3321	(make-local-variable 'gud-tooltip-mouse-motions-active)
3322	(setq gud-tooltip-mouse-motions-active t)
3323	(make-local-variable 'track-mouse)
3324	(setq track-mouse t))
3325    (when gud-tooltip-mouse-motions-active
3326      (kill-local-variable 'gud-tooltip-mouse-motions-active)
3327      (kill-local-variable 'track-mouse))))
3328
3329(defun gud-tooltip-mouse-motion (event)
3330  "Command handler for mouse movement events in `global-map'."
3331  (interactive "e")
3332  (tooltip-hide)
3333  (when (car (mouse-pixel-position))
3334    (setq tooltip-last-mouse-motion-event (copy-sequence event))
3335    (tooltip-start-delayed-tip)))
3336
3337;;; Tips for `gud'
3338
3339(defvar gud-tooltip-original-filter nil
3340  "Process filter to restore after GUD output has been received.")
3341
3342(defvar gud-tooltip-dereference nil
3343  "Non-nil means print expressions with a `*' in front of them.
3344For C this would dereference a pointer expression.")
3345
3346(defvar gud-tooltip-event nil
3347  "The mouse movement event that led to a tooltip display.
3348This event can be examined by forms in GUD-TOOLTIP-DISPLAY.")
3349
3350(defun gud-tooltip-dereference (&optional arg)
3351  "Toggle whether tooltips should show `* expr' or `expr'.
3352With arg, dereference expr iff arg is positive."
3353 (interactive "P")
3354  (setq gud-tooltip-dereference
3355	(if (null arg)
3356	    (not gud-tooltip-dereference)
3357	  (> (prefix-numeric-value arg) 0)))
3358  (message "Dereferencing is now %s."
3359	   (if gud-tooltip-dereference "on" "off")))
3360
3361(define-obsolete-function-alias 'tooltip-gud-toggle-dereference
3362                                'gud-tooltip-dereference "22.1")
3363
3364; This will only display data that comes in one chunk.
3365; Larger arrays (say 400 elements) are displayed in
3366; the tooltip incompletely and spill over into the gud buffer.
3367; Switching the process-filter creates timing problems and
3368; it may be difficult to do better. Using annotations as in
3369; gdb-ui.el gets round this problem.
3370(defun gud-tooltip-process-output (process output)
3371  "Process debugger output and show it in a tooltip window."
3372  (set-process-filter process gud-tooltip-original-filter)
3373  (tooltip-show (tooltip-strip-prompt process output)
3374		(or gud-tooltip-echo-area tooltip-use-echo-area)))
3375
3376(defun gud-tooltip-print-command (expr)
3377  "Return a suitable command to print the expression EXPR."
3378  (case gud-minor-mode
3379	(gdba (concat "server print " expr))
3380	((dbx gdbmi) (concat "print " expr))
3381	((xdb pdb) (concat "p " expr))
3382	(sdb (concat expr "/"))))
3383
3384(defun gud-tooltip-tips (event)
3385  "Show tip for identifier or selection under the mouse.
3386The mouse must either point at an identifier or inside a selected
3387region for the tip window to be shown.  If gud-tooltip-dereference is t,
3388add a `*' in front of the printed expression. In the case of a C program
3389controlled by GDB, show the associated #define directives when program is
3390not executing.
3391
3392This function must return nil if it doesn't handle EVENT."
3393  (let (process)
3394    (when (and (eventp event)
3395	       gud-tooltip-mode
3396	       gud-comint-buffer
3397	       (buffer-name gud-comint-buffer); might be killed
3398	       (setq process (get-buffer-process gud-comint-buffer))
3399	       (posn-point (event-end event))
3400	       (or (and (eq gud-minor-mode 'gdba) (not gdb-active-process))
3401		   (progn (setq gud-tooltip-event event)
3402			  (eval (cons 'and gud-tooltip-display)))))
3403      (let ((expr (tooltip-expr-to-print event)))
3404	(when expr
3405	  (if (and (eq gud-minor-mode 'gdba)
3406		   (not gdb-active-process))
3407	      (progn
3408		(with-current-buffer
3409		    (window-buffer (let ((mouse (mouse-position)))
3410				     (window-at (cadr mouse)
3411						(cddr mouse))))
3412		  (let ((define-elt (assoc expr gdb-define-alist)))
3413		    (unless (null define-elt)
3414		      (tooltip-show
3415		       (cdr define-elt)
3416		       (or gud-tooltip-echo-area tooltip-use-echo-area))
3417		      expr))))
3418	    (when gud-tooltip-dereference
3419	      (setq expr (concat "*" expr)))
3420	    (let ((cmd (gud-tooltip-print-command expr)))
3421	      (when (and gud-tooltip-mode (eq gud-minor-mode 'gdb))
3422		(gud-tooltip-mode -1)
3423		(message-box "Using GUD tooltips in this mode is unsafe\n\
3424so they have been disabled."))
3425	      (unless (null cmd) ; CMD can be nil if unknown debugger
3426		(if (memq gud-minor-mode '(gdba gdbmi))
3427		      (if gdb-macro-info
3428			  (gdb-enqueue-input
3429			   (list (concat
3430				  gdb-server-prefix "macro expand " expr "\n")
3431				 `(lambda () (gdb-tooltip-print-1 ,expr))))
3432			(gdb-enqueue-input
3433			 (list  (concat cmd "\n")
3434 				 `(lambda () (gdb-tooltip-print ,expr)))))
3435		  (setq gud-tooltip-original-filter (process-filter process))
3436		  (set-process-filter process 'gud-tooltip-process-output)
3437		  (gud-basic-call cmd))
3438		expr))))))))
3439
3440(provide 'gud)
3441
3442;;; arch-tag: 6d990948-df65-461a-be39-1c7fb83ac4c4
3443;;; gud.el ends here
3444