idlw-shell.el 137 KB
Newer Older
1
;; idlw-shell.el --- run IDL as an inferior process of Emacs.
2
;; Copyright (c) 1999, 2000, 2001,2002 Free Software Foundation
3 4 5 6

;; Author: Carsten Dominik <dominik@astro.uva.nl>
;;         Chris Chase <chase@att.com>
;; Maintainer: J.D. Smith <jdsmith@as.arizona.edu>
7
;; Version: 4.15
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
;; Keywords: processes

;; This file is part of GNU Emacs.

;; GNU Emacs is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 2, or (at your option)
;; any later version.

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs; see the file COPYING.  If not, write to the
;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
;; Boston, MA 02111-1307, USA.

;;; Commentary:
28 29 30 31
;;
;; This mode is for IDL version 5 or later.  It should work on
;; Emacs>20.3 or XEmacs>20.4.
;;
32 33 34 35 36 37 38 39
;; Runs IDL as an inferior process of Emacs, much like the emacs
;; `shell' or `telnet' commands.  Provides command history and
;; searching.  Provides debugging commands available in buffers
;; visiting IDL procedure files, e.g., breakpoint setting, stepping,
;; execution until a certain line, printing expressions under point,
;; visual line pointer for current execution line, etc.
;;
;; Documentation should be available online with `M-x idlwave-info'.
40 41 42 43 44
;;
;; New versions of IDLWAVE, documentation, and more information
;; available from:
;;                 http://idlwave.org
;;
45 46
;; INSTALLATION:
;; =============
47
;;
48 49 50 51 52 53 54 55 56 57 58 59
;; Follow the instructions in the INSTALL file of the distribution.
;; In short, put this file on your load path and add the following
;; lines to your .emacs file:
;;
;; (autoload 'idlwave-shell "idlw-shell" "IDLWAVE Shell" t)
;;
;;
;; SOURCE
;; ======
;;
;;   The newest version of this file can be found on the maintainers
;;   web site.
60
;;
61
;;     http://idlwave.org
62
;;
63 64 65 66 67 68 69 70 71 72 73 74 75 76
;; DOCUMENTATION
;; =============
;;
;; IDLWAVE is documented online in info format.
;; A printable version of the documentation is available from the
;; maintainers webpage (see under SOURCE)
;;
;;
;; KNOWN PROBLEMS
;; ==============
;;
;; Under XEmacs the Debug menu in the shell does not display the
;; keybindings in the prefix map.  There bindings are available anyway - so
;; it is a bug in XEmacs.
77
;; The Debug menu in source buffers *does* display the bindings correctly.
78
;;
79
;;
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
;; CUSTOMIZATION VARIABLES
;; =======================
;;
;; IDLWAVE has customize support - so if you want to learn about
;; the variables which control the behavior of the mode, use
;; `M-x idlwave-customize'.
;;
;;--------------------------------------------------------------------------
;;

;;; Code:

(require 'comint)
(require 'idlwave)

(eval-when-compile (require 'cl))

(defvar idlwave-shell-have-new-custom nil)
(eval-and-compile
99 100 101 102
  ;; Kludge to allow `defcustom' for Emacs 19.
  (condition-case () (require 'custom) (error nil))
  (if (and (featurep 'custom)
	   (fboundp 'custom-declare-variable)
103
	   (fboundp 'defface))
104 105 106 107
      ;; We've got what we needed
      (setq idlwave-shell-have-new-custom t)
    ;; We have the old or no custom-library, hack around it!
    (defmacro defgroup (&rest args) nil)
108
    (defmacro defcustom (var value doc &rest args)
109
      `(defvar ,var ,value ,doc))))
110 111 112

;;; Customizations: idlwave-shell group

113
;; General/Misc. customizations
114
(defgroup idlwave-shell-general-setup nil
115 116
  "General setup of the Shell interaction for IDLWAVE/Shell."
  :prefix "idlwave-shell"
117 118 119
  :group 'idlwave)

(defcustom idlwave-shell-prompt-pattern "^ ?IDL> "
120 121
  "*Regexp to match IDL prompt at beginning of a line.
For example, \"^IDL> \" or \"^WAVE> \".
122
The \"^\" means beginning of line.
123
This variable is used to initialise `comint-prompt-regexp' in the
124 125 126 127 128 129 130 131 132 133 134 135
process buffer.

This is a fine thing to set in your `.emacs' file."
  :group 'idlwave-shell-general-setup
  :type 'regexp)

(defcustom idlwave-shell-process-name "idl"
  "*Name to be associated with the IDL process.  The buffer for the
process output is made by surrounding this name with `*'s."
  :group 'idlwave-shell-general-setup
  :type 'string)

136
;; (defcustom idlwave-shell-automatic-start...)  See idlwave.el
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151

(defcustom idlwave-shell-use-dedicated-frame nil
  "*Non-nil means, IDLWAVE should use a special frame to display shell buffer."
  :group 'idlwave-shell-general-setup
  :type 'boolean)

(defcustom idlwave-shell-frame-parameters
  '((height . 30) (unsplittable . nil))
  "The frame parameters for a dedicated idlwave-shell frame.
See also `idlwave-shell-use-dedicated-frame'.
The default makes the frame splittable, so that completion works correctly."
  :group 'idlwave-shell-general-setup
  :type '(repeat
	  (cons symbol sexp)))

152 153 154 155 156
(defcustom idlwave-shell-raise-frame t
  "*Non-nil means, `idlwave-shell' raises the frame showing the shell window."
  :group 'idlwave-shell-general-setup
  :type 'boolean)

157 158 159 160 161 162 163 164 165 166 167 168 169 170
(defcustom idlwave-shell-arrows-do-history t
  "*Non-nil means UP and DOWN arrows move through command history.
This variable can have 3 values:
nil        Arrows just move the cursor
t          Arrows force the cursor back to the current command line and
           walk the history
'cmdline   When the cursor is in the current command line, arrows walk the
           history.  Everywhere else in the buffer, arrows move the cursor."
  :group 'idlwave-shell-general-setup
  :type '(choice
	  (const :tag "never" nil)
	  (const :tag "everywhere" t)
	  (const :tag "in command line only" cmdline)))

171 172
;; FIXME: add comint-input-ring-size?

173
(defcustom idlwave-shell-use-toolbar t
174
  "*Non-nil means, use the debugging toolbar in all IDL related buffers.
175 176
Starting the shell will then add the toolbar to all idlwave-mode buffers.
Exiting the shell will removed everywhere.
177
Available on XEmacs and on Emacs 21.x or later.
178 179
At any time you can toggle the display of the toolbar with
`C-c C-d C-t' (`idlwave-shell-toggle-toolbar')."
180 181 182 183 184 185
  :group 'idlwave-shell-general-setup
  :type 'boolean)

(defcustom idlwave-shell-temp-pro-prefix "/tmp/idltemp"
  "*The prefix for temporary IDL files used when compiling regions.
It should be an absolute pathname.
186
The full temporary file name is obtained by using `make-temp-file'
187 188 189 190 191 192 193 194 195 196 197 198 199
so that the name will be unique among multiple Emacs processes."
  :group 'idlwave-shell-general-setup
  :type 'string)

(defvar idlwave-shell-fix-inserted-breaks nil
  "*OBSOLETE VARIABLE, is no longer used.

The documentation of this variable used to be:
If non-nil then run `idlwave-shell-remove-breaks' to clean up IDL messages.")

(defcustom idlwave-shell-prefix-key "\C-c\C-d"
  "*The prefix key for the debugging map `idlwave-shell-mode-prefix-map'.
This variable must already be set when idlwave-shell.el is loaded.
200
Setting it in the mode-hook is too late."
201 202 203 204 205 206 207 208 209 210
  :group 'idlwave-shell-general-setup
  :type 'string)

(defcustom idlwave-shell-activate-prefix-keybindings t
  "Non-nil means, the debug commands will be bound to the prefix key.
The prefix key itself is given in the option `idlwave-shell-prefix-key'.
So by default setting a breakpoint will be on C-c C-d C-b."
  :group 'idlwave-shell-general-setup
  :type 'boolean)

211 212 213 214
;; (defcustom idlwave-shell-debug-modifiers... See idlwave.el

(defvar idlwave-shell-activate-alt-keybindings nil
  "Obsolete variable.  See `idlwave-shell-debug-modifiers'.")
215 216 217 218 219 220

(defcustom idlwave-shell-use-truename nil
  "*Non-nil means, use use `file-truename' when looking for buffers.
If this variable is non-nil, Emacs will use the function `file-truename' to
resolve symbolic links in the file paths printed by e.g., STOP commands.
This means, unvisited files will be loaded under their truename.
221
However, when a file is already visited under a different name, IDLWAVE will
222 223 224 225 226 227 228
reuse that buffer.
This option was once introduced in order to avoid multiple buffers visiting
the same file.  However, IDLWAVE no longer makes this mistake, so it is safe
to set this option to nil."
  :group 'idlwave-shell-general-setup
  :type 'boolean)

229
(defcustom idlwave-shell-file-name-chars "~/A-Za-z0-9+:_.$#%={}\\-"
230 231 232 233 234 235 236 237 238 239 240
  "The characters allowed in file names, as a string.
Used for file name completion. Must not contain `'', `,' and `\"'
because these are used as separators by IDL."
  :group 'idlwave-shell-general-setup
  :type 'string)

(defcustom idlwave-shell-mode-hook '()
  "*Hook for customising `idlwave-shell-mode'."
  :group 'idlwave-shell-general-setup
  :type 'hook)

241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
(defcustom idlwave-shell-graphics-window-size '(500 400)
  "Size of IDL graphics windows popped up by special IDLWAVE command.
The command is `C-c C-d C-f' and accepts as a prefix the window nr.
A command like `WINDOW,N,xsize=XX,ysize=YY' is sent to IDL."
  :group 'idlwave-shell-general-setup
  :type '(list
	  (integer :tag "x size")
	  (integer :tag "y size")))

;; Commands Sent to Shell... etc.
(defgroup idlwave-shell-command-setup nil
  "Setup for command parameters of the Shell interaction for IDLWAVE."
  :prefix "idlwave-shell"
  :group 'idlwave)

(defcustom idlwave-shell-initial-commands "!more=0"
  "Initial commands, separated by newlines, to send to IDL.
This string is sent to the IDL process by `idlwave-shell-mode' which is
invoked by `idlwave-shell'."
  :group 'idlwave-shell-command-setup
  :type 'string)

(defcustom idlwave-shell-save-command-history t
  "Non-nil means preserve command history between sessions.
The file `idlwave-shell-command-history-file' is used to save and restore
the history."
  :group 'idlwave-shell-command-setup
  :type 'boolean)

(defcustom idlwave-shell-command-history-file "~/.idlwhist"
  "The file in which the command history of the idlwave shell is saved.
In order to change the size of the history, see the variable
`comint-input-ring-size'.
The history is only saved if the variable `idlwave-shell-save-command-history'
is non-nil."
  :group 'idlwave-shell-command-setup
  :type 'file)
278

279 280
(defcustom idlwave-shell-show-commands
  '(run misc breakpoint)
281
  "*A list of command types to show output from in the shell.
282 283 284 285 286 287 288 289 290 291 292
Possibilities are 'run, 'debug, 'breakpoint, and 'misc .  Unlisted
types are not displayed in the shell.  The single type 'everything
causes all the copious shell traffic to be displayed."
  :group 'idlwave-shell-command-setup
  :type '(choice
	  (const everything)
	  (set :tag "Checklist" :greedy t
	       (const :tag "All .run and .compile commands"  run)
	       (const :tag "All breakpoint commands"         breakpoint)
	       (const :tag "All debug and stepping commands" debug)
	       (const :tag "Return, close, etc. commands"    misc))))
293

294
(defcustom idlwave-shell-examine-alist
295 296 297 298 299 300 301 302 303 304
  '(("Print"          	. "print,___")
    ("Help"           	. "help,___")
    ("Structure Help"  	. "help,___,/STRUCTURE")
    ("Dimensions"     	. "print,size(___,/DIMENSIONS)")
    ("Type"           	. "print,size(___,/TNAME)")
    ("N_Elements"     	. "print,n_elements(___)")
    ("All Size Info"  	. "help,(__IWsz__=size(___,/STRUCTURE)),/STRUCTURE & print,__IWsz__.DIMENSIONS")
    ("Ptr Valid"      	. "print,ptr_valid(___)")
    ("Widget Valid"     . "print,widget_info(___,/VALID)")
    ("Widget Geometry"  . "help,widget_info(___,/GEOMETRY)"))
305
  "Alist of special examine commands for popup selection.
306 307 308 309
The keys are used in the selection popup created by
`idlwave-shell-examine-select', and the corresponding value is sent as
a command to the shell, with special sequence `___' replaced by the
expression being examined."
310
  :group 'idlwave-shell-command-setup
311
  :type '(repeat
312
	  (cons
313 314
	   (string :tag "Label  ")
	   (string :tag "Command"))))
315

316 317 318
(defvar idlwave-shell-print-expression-function nil
  "*OBSOLETE VARIABLE, is no longer used.")

319 320
(defcustom idlwave-shell-separate-examine-output t
  "*Non-nil mean, put output of examine commands in their own buffer."
321
  :group 'idlwave-shell-command-setup
322
  :type 'boolean)
323

324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
(defcustom idlwave-shell-comint-settings
  '((comint-scroll-to-bottom-on-input . t)
    (comint-scroll-to-bottom-on-output . t)
    (comint-scroll-show-maximum-output . nil))

  "Alist of special settings for the comint variables in the IDLWAVE Shell.
Each entry is a cons cell with the name of a variable and a value.
The function `idlwave-shell-mode' will make local variables out of each entry.
Changes to this variable will only be active when the shell buffer is
newly created."
  :group 'idlwave-shell-command-setup
  :type '(repeat
	  (cons variable sexp)))

(defcustom idlwave-shell-query-for-class t
  "*Non-nil means query the shell for object class on object completions."
  :group 'idlwave-shell-command-setup
  :type 'boolean)

343 344 345 346 347 348
(defcustom idlwave-shell-use-input-mode-magic nil
  "*Non-nil means, IDLWAVE should check for input mode spells in output.
The spells are strings printed by your IDL program and matched
by the regular expressions in `idlwave-shell-input-mode-spells'.
When these expressions match, IDLWAVE switches to character input mode and
back, respectively.  See `idlwave-shell-input-mode-spells' for details."
349
  :group 'idlwave-shell-command-setup
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
  :type 'boolean)

(defcustom idlwave-shell-input-mode-spells
  '("^<onechar>$" "^<chars>$" "^</chars>$")
  "The three regular expressions which match the magic spells for input modes.

When the first regexp matches in the output streem of IDL, IDLWAVE
prompts for a single character and sends it immediately to IDL, similar
to the command \\[idlwave-shell-send-char].

When the second regexp matches, IDLWAVE switches to a blocking
single-character input mode.  This is the same mode which can be entered
manually with \\[idlwave-shell-char-mode-loop].
This input mode exits when the third regexp matches in the output,
or when the IDL prompt is encountered.

The variable `idlwave-shell-use-input-mode-magic' must be non-nil to enable
scanning for these expressions.  If the IDL program produces lots of
output, shell operation may be slowed down.

This mechanism is useful for correct interaction with the IDL function
GET_KBRD, because in normal operation IDLWAVE only sends \\n terminated
372
strings.  Here is some example code which makes use of the default spells.
373 374 375 376 377 378 379 380 381 382 383 384 385

  print,'<chars>'               ; Make IDLWAVE switch to character mode
  REPEAT BEGIN
      A = GET_KBRD(1)
      PRINT, BYTE(A)
  ENDREP UNTIL A EQ 'q'
  print,'</chars>'              ; Make IDLWAVE switch back to line mode

  print,'Quit the program, y or n?'
  print,'<onechar>'             ; Ask IDLWAVE to send one character
  answer = GET_KBRD(1)

Since the IDLWAVE shell defines the system variable `!IDLWAVE_VERSION',
386
you could actually check if you are running under Emacs before printing
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
the magic strings.  Here is a procedure which uses this.

Usage:
======
idlwave_char_input               ; Make IDLWAVE send one character
idlwave_char_input,/on           ; Start the loop to send characters
idlwave_char_input,/off          ; End the loop to send chracters


pro idlwave_char_input,on=on,off=off
  ;; Test if we are running under Emacs
  defsysv,'!idlwave_version',exists=running_emacs
  if running_emacs then begin
      if keyword_set(on) then         print,'<chars>' $
        else if keyword_set(off) then print,'</chars>' $
        else                          print,'<onechar>'
403
  endif
404
end"
405
  :group 'idlwave-shell-command-setup
406 407 408 409 410
  :type '(list
	  (regexp :tag "One-char  regexp")
	  (regexp :tag "Char-mode regexp")
	  (regexp :tag "Line-mode regexp")))

411

412
;; Breakpoint Overlays etc
413
(defgroup idlwave-shell-highlighting-and-faces nil
414 415
  "Highlighting and Faces used by the IDLWAVE Shell mode."
  :prefix "idlwave-shell"
416 417 418 419 420 421 422 423 424 425
  :group 'idlwave)

(defcustom idlwave-shell-mark-stop-line t
  "*Non-nil means, mark the source code line where IDL is currently stopped.
Value decides about the method which is used to mark the line.  Legal values
are:

nil       Do not mark the line
'arrow    Use the overlay arrow
'face     Use `idlwave-shell-stop-line-face' to highlight the line.
426
t         Use what IDLWAVE thinks is best.  Will be a face where possible,
427 428 429 430
          otherwise the overlay arrow.
The overlay-arrow has the disadvantage to hide the first chars of a line.
Since many people do not have the main block of IDL programs indented,
a face highlighting may be better.
431
In Emacs 21, the overlay arrow is displayed in a special area and never
432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
hides any code, so setting this to 'arrow on Emacs 21 sounds like a good idea."
  :group 'idlwave-shell-highlighting-and-faces
  :type '(choice
	  (const :tag "No marking" nil)
	  (const :tag "Use overlay arrow" arrow)
	  (const :tag "Highlight with face" face)
	  (const :tag "Face or arrow." t)))

(defcustom idlwave-shell-overlay-arrow ">"
  "*The overlay arrow to display at source lines where execution halts.
We use a single character by default, since the main block of IDL procedures
often has no indentation.  Where possible, IDLWAVE will use overlays to
display the stop-lines.  The arrow is only used on character-based terminals.
See also `idlwave-shell-use-overlay-arrow'."
  :group 'idlwave-shell-highlighting-and-faces
  :type 'string)

(defcustom idlwave-shell-stop-line-face 'highlight
  "*The face for `idlwave-shell-stop-line-overlay'.
Allows you to choose the font, color and other properties for
line where IDL is stopped.  See also `idlwave-shell-mark-stop-line'."
  :group 'idlwave-shell-highlighting-and-faces
  :type 'symbol)

(defcustom idlwave-shell-mark-breakpoints t
  "*Non-nil means, mark breakpoints in the source files.
Legal values are:
nil        Do not mark breakpoints.
'face      Highlight line with `idlwave-shell-breakpoint-face'.
'glyph     Red dot at the beginning of line.  If the display does not
           support glyphs, will use 'face instead.
t          Glyph when possible, otherwise face (same effect as 'glyph)."
  :group 'idlwave-shell-highlighting-and-faces
  :type '(choice
	  (const :tag "No marking" nil)
	  (const :tag "Highlight with face" face)
	  (const :tag "Display glyph (red dot)" glyph)
	  (const :tag "Glyph or face." t)))

(defvar idlwave-shell-use-breakpoint-glyph t
472
  "Obsolete variable.  See `idlwave-shell-mark-breakpoints.")
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490

(defcustom idlwave-shell-breakpoint-face 'idlwave-shell-bp-face
  "*The face for breakpoint lines in the source code.
Allows you to choose the font, color and other properties for
lines which have a breakpoint.  See also `idlwave-shell-mark-breakpoints'."
  :group 'idlwave-shell-highlighting-and-faces
  :type 'symbol)

(if idlwave-shell-have-new-custom
    ;; We have the new customize - use it to define a customizable face
    (defface idlwave-shell-bp-face
      '((((class color)) (:foreground "Black" :background "Pink"))
	(t (:underline t)))
      "Face for highlighting lines-with-breakpoints."
      :group 'idlwave-shell-highlighting-and-faces)
  ;; Just copy the underline face to be on the safe side.
  (copy-face 'underline 'idlwave-shell-bp-face))

491 492 493 494 495 496 497
(defcustom idlwave-shell-expression-face 'secondary-selection
  "*The face for `idlwave-shell-expression-overlay'.
Allows you to choose the font, color and other properties for
the expression printed by IDL."
  :group 'idlwave-shell-highlighting-and-faces
  :type 'symbol)

498 499 500 501 502 503 504
(defcustom idlwave-shell-output-face 'secondary-selection
  "*The face for `idlwave-shell-output-overlay'.
Allows you to choose the font, color and other properties for
the expression output by IDL."
  :group 'idlwave-shell-highlighting-and-faces
  :type 'symbol)

505 506 507 508 509 510
;;; End user customization variables

;;; External variables
(defvar comint-last-input-start)
(defvar comint-last-input-end)

511 512 513 514 515
(defun idlwave-shell-temp-file (type)
  "Return a temp file, creating it if necessary.

TYPE is either 'pro or 'rinfo, and idlwave-shell-temp-pro-file or
idlwave-shell-temp-rinfo-save-file is set (respectively)."
516
  (cond
517
   ((eq type 'rinfo)
518 519
    (or idlwave-shell-temp-rinfo-save-file
	(setq idlwave-shell-temp-rinfo-save-file
520 521 522
	      (idlwave-shell-make-temp-file idlwave-shell-temp-pro-prefix))))
   ((eq type 'pro)
    (or idlwave-shell-temp-pro-file
523
	(setq idlwave-shell-temp-pro-file
524
	      (idlwave-shell-make-temp-file idlwave-shell-temp-pro-prefix))))
525
   (t (error "Wrong argument (idlwave-shell-temp-file): %s"
526
	     (symbol-name type)))))
527

528

529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
(defun idlwave-shell-make-temp-file (prefix)
  "Create a temporary file."
  ; Hard coded make-temp-file for Emacs<21
  (if (fboundp 'make-temp-file)
      (make-temp-file prefix)
    (let (file
	  (temp-file-dir (if (boundp 'temporary-file-directory)
			     temporary-file-directory
			   "/tmp")))
      (while (condition-case ()
		 (progn
		   (setq file
			 (make-temp-name
			  (expand-file-name prefix temp-file-dir)))
                   (if (featurep 'xemacs)
		       (write-region "" nil file nil 'silent nil)
		     (write-region "" nil file nil 'silent nil 'excl))
		   nil)
	       (file-already-exists t))
	;; the file was somehow created by someone else between
	;; `make-temp-name' and `write-region', let's try again.
	nil)
      file)))
552

553 554 555
;; Other variables
(defvar idlwave-shell-temp-pro-file
  nil
556 557
  "Absolute pathname for temporary IDL file for compiling regions")

558
(defvar idlwave-shell-temp-rinfo-save-file
559
  nil
560 561 562 563
  "Absolute pathname for temporary IDL file save file for routine_info.
This is used to speed up the reloading of the routine info procedure
before use by the shell.")

564
(defvar idlwave-shell-dirstack-query "cd,current=___cur & print,___cur"
565
  "Command used by `idlwave-shell-resync-dirs' to query IDL for
566 567
the directory stack.")

568
(defvar idlwave-shell-path-query "__pa=expand_path(!path,/array)&for i=0,n_elements(__pa)-1 do print,'PATH:<'+__pa[i]+'>'&print,'SYSDIR:<'+!dir+'>'"
569 570
  "The command which gets !PATH and !DIR infor from the shell.")

571
(defvar idlwave-shell-mode-line-info nil
572
  "Additional info displayed in the mode line")
573

574 575 576 577 578 579 580 581 582 583 584 585 586 587
(defvar idlwave-shell-default-directory nil
  "The default directory in the idlwave-shell buffer, of outside use.")

(defvar idlwave-shell-last-save-and-action-file nil
  "The last file which was compiled with `idlwave-shell-save-and-...'.")

;; Highlighting uses overlays.  When necessary, require the emulation.
(if (not (fboundp 'make-overlay))
    (condition-case nil
	(require 'overlay)
      (error nil)))

(defvar idlwave-shell-stop-line-overlay nil
  "The overlay for where IDL is currently stopped.")
588
(defvar idlwave-shell-is-stopped nil)
589 590
(defvar idlwave-shell-expression-overlay nil
  "The overlay for where IDL is currently stopped.")
591 592 593
(defvar idlwave-shell-output-overlay nil
  "The overlay for the last IDL output.")

594 595 596 597 598 599
;; If these were already overlays, delete them.  This probably means that we
;; are reloading this file.
(if (overlayp idlwave-shell-stop-line-overlay)
    (delete-overlay idlwave-shell-stop-line-overlay))
(if (overlayp idlwave-shell-expression-overlay)
    (delete-overlay idlwave-shell-expression-overlay))
600 601 602
(if (overlayp idlwave-shell-output-overlay)
    (delete-overlay idlwave-shell-output-overlay))

603 604
;; Set to nil initially
(setq idlwave-shell-stop-line-overlay nil
605 606
      idlwave-shell-expression-overlay nil
      idlwave-shell-output-overlay nil)
607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622

;; Define the shell stop overlay.  When left nil, the arrow will be used.
(cond
 ((or (null idlwave-shell-mark-stop-line)
      (eq idlwave-shell-mark-stop-line 'arrow))
  ;; Leave the overlay nil
  nil)

 ((eq idlwave-shell-mark-stop-line 'face)
  ;; Try to use a face.  If not possible, arrow will be used anyway
  ;; So who can display faces?
  (when (or (featurep 'xemacs)            ; XEmacs can do also ttys
	    (fboundp 'tty-defined-colors) ; Emacs 21 as well
	    window-system)                ; Window systems always
    (progn
      (setq idlwave-shell-stop-line-overlay (make-overlay 1 1))
623
      (overlay-put idlwave-shell-stop-line-overlay
624 625 626 627 628 629 630
		   'face idlwave-shell-stop-line-face))))

 (t
  ;; IDLWAVE may decide.  Will use a face on window systems, arrow elsewhere
  (if window-system
      (progn
	(setq idlwave-shell-stop-line-overlay (make-overlay 1 1))
631
	(overlay-put idlwave-shell-stop-line-overlay
632 633
		     'face idlwave-shell-stop-line-face)))))

634
;; Now the expression and output overlays
635 636 637
(setq idlwave-shell-expression-overlay (make-overlay 1 1))
(overlay-put idlwave-shell-expression-overlay
	     'face idlwave-shell-expression-face)
638 639 640 641
(setq idlwave-shell-output-overlay (make-overlay 1 1))
(overlay-put idlwave-shell-output-overlay
	     'face idlwave-shell-output-face)

642 643 644 645 646 647 648 649 650 651 652
(defvar idlwave-shell-bp-query "help,/breakpoints"
  "Command to obtain list of breakpoints")

(defvar idlwave-shell-command-output nil
  "String for accumulating current command output.")

(defvar idlwave-shell-post-command-hook nil
  "Lisp list expression or function to run when an IDL command is finished.
The current command is finished when the IDL prompt is displayed.
This is evaluated if it is a list or called with funcall.")

653 654 655
(defvar idlwave-shell-sentinel-hook nil
  "Hook run when the idl process exits.")

656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682
(defvar idlwave-shell-hide-output nil
  "If non-nil the process output is not inserted into the output
  buffer.")

(defvar idlwave-shell-accumulation nil
  "Accumulate last line of output.")

(defvar idlwave-shell-command-line-to-execute nil)
(defvar idlwave-shell-cleanup-hook nil
  "List of functions to do cleanup when the shell exits.")

(defvar idlwave-shell-pending-commands nil
  "List of commands to be sent to IDL.
Each element of the list is list of \(CMD PCMD HIDE\), where CMD is a
string to be sent to IDL and PCMD is a post-command to be placed on
`idlwave-shell-post-command-hook'. If HIDE is non-nil, hide the output
from command CMD. PCMD and HIDE are optional.")

(defun idlwave-shell-buffer ()
  "Name of buffer associated with IDL process.
The name of the buffer is made by surrounding `idlwave-shell-process-name
with `*'s."
  (concat "*" idlwave-shell-process-name "*"))

(defvar idlwave-shell-ready nil
  "If non-nil can send next command to IDL process.")

683 684 685
(defvar idlwave-shell-wait-for-output nil
  "Whether to wait for output to accumulate.")

686 687
;;; The following are the types of messages we attempt to catch to
;;; resync our idea of where IDL execution currently is.
688
;;;
689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744

(defvar idlwave-shell-halt-frame nil
  "The frame associated with halt/breakpoint messages.")

(defvar idlwave-shell-step-frame nil
  "The frame associated with step messages.")

(defvar idlwave-shell-trace-frame nil
  "The frame associated with trace messages.")

(defconst idlwave-shell-halt-messages
  '("^% Execution halted at"
    "^% Interrupted at:"
    "^% Stepped to:"
    "^% At "
    "^% Stop encountered:"
    )
  "*A list of regular expressions matching IDL messages.
These are the messages containing file and line information where
IDL is currently stopped.")

(defconst idlwave-shell-halt-messages-re
  (mapconcat 'identity idlwave-shell-halt-messages "\\|")
  "The regular expression computed from idlwave-shell-halt-messages")

(defconst idlwave-shell-trace-messages
  '("^% At "    ;; First line of a trace message
    )
  "*A list of regular expressions matching IDL trace messages.
These are the messages containing file and line information where
IDL will begin looking for the next statement to execute.")

(defconst idlwave-shell-step-messages
  '("^% Stepped to:"
    )
  "*A list of regular expressions matching stepped execution messages.
These are IDL messages containing file and line information where
IDL has currently stepped.")

(defvar idlwave-shell-break-message "^% Breakpoint at:"
  "*Regular expression matching an IDL breakpoint message line.")


(defvar idlwave-shell-bp-alist)
;(defvar idlwave-shell-post-command-output)
(defvar idlwave-shell-sources-alist)
(defvar idlwave-shell-menu-def)
(defvar idlwave-shell-mode-menu)
(defvar idlwave-shell-initial-commands)
(defvar idlwave-shell-syntax-error)
(defvar idlwave-shell-other-error)
(defvar idlwave-shell-error-buffer)
(defvar idlwave-shell-error-last)
(defvar idlwave-shell-bp-buffer)
(defvar idlwave-shell-sources-query)
(defvar idlwave-shell-mode-map)
745
(defvar idlwave-shell-calling-stack-index)
746 747 748 749 750 751 752 753 754 755 756 757 758

(defun idlwave-shell-mode ()
  "Major mode for interacting with an inferior IDL process.

1. Shell Interaction
   -----------------
   RET after the end of the process' output sends the text from the
   end of process to the end of the current line.  RET before end of
   process output copies the current line (except for the prompt) to the
   end of the buffer.

   Command history, searching of previous commands, command line
   editing are available via the comint-mode key bindings, by default
759 760
   mostly on the key `C-c'.  Command history is also available with
   the arrow keys UP and DOWN.
761 762 763

2. Completion
   ----------
764 765 766 767
   TAB and M-TAB do completion of IDL routines, classes and keywords -
   similar to M-TAB in `idlwave-mode'.  In executive commands and
   strings, it completes file names.  Abbreviations are also expanded
   like in `idlwave-mode'.
768 769 770 771 772 773

3. Routine Info
   ------------
   `\\[idlwave-routine-info]' displays information about an IDL routine near point,
   just like in `idlwave-mode'.  The module used is the one at point or
   the one whose argument list is being edited.
774
   To update IDLWAVE's knowledge about compiled or edited modules, use
775 776 777
   \\[idlwave-update-routine-info].
   \\[idlwave-find-module] find the source of a module.
   \\[idlwave-resolve] tells IDL to compile an unresolved module.
778 779
   \\[idlwave-context-help] shows the online help on the item at
   point, if online help has been installed.
780

781 782 783 784

4. Debugging
   ---------
   A complete set of commands for compiling and debugging IDL programs
785
   is available from the menu.  Also keybindings starting with a
786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809
   `C-c C-d' prefix are available for most commands in the *idl* buffer
   and also in source buffers.  The best place to learn about the
   keybindings is again the menu.

   On Emacs versions where this is possible, a debugging toolbar is
   installed.

   When IDL is halted in the middle of a procedure, the corresponding
   line of that procedure file is displayed with an overlay in another
   window.  Breakpoints are also highlighted in the source.

   \\[idlwave-shell-resync-dirs] queries IDL in order to change Emacs current directory
   to correspond to the IDL process current directory.

5. Hooks
   -----
   Turning on `idlwave-shell-mode' runs `comint-mode-hook' and
   `idlwave-shell-mode-hook' (in that order).

6. Documentation and Customization
   -------------------------------
   Info documentation for this package is available.  Use \\[idlwave-info]
   to display (complain to your sysadmin if that does not work).
   For Postscript and HTML versions of the documentation, check IDLWAVE's
810
   homepage at `http://idlwave.org'.
811 812 813 814 815 816 817
   IDLWAVE has customize support - see the group `idlwave'.

7. Keybindings
   -----------
\\{idlwave-shell-mode-map}"

  (interactive)
818 819
  ;; We don't do `kill-all-local-variables' here, because this is done by
  ;; comint - idlwave-shell-mode only add on top of that.
820 821 822 823
  (setq comint-prompt-regexp idlwave-shell-prompt-pattern)
  (setq comint-process-echoes t)
  ;; Can not use history expansion because "!" is used for system variables.
  (setq comint-input-autoexpand nil)
824
;  (setq comint-input-ring-size 64)
825 826 827 828 829 830
  (make-local-variable 'comint-completion-addsuffix)
  (set (make-local-variable 'completion-ignore-case) t)
  (setq comint-completion-addsuffix '("/" . ""))
  (setq comint-input-ignoredups t)
  (setq major-mode 'idlwave-shell-mode)
  (setq mode-name "IDL-Shell")
831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849
  (setq idlwave-shell-mode-line-info nil)
  (setq mode-line-format
	'(""
	  mode-line-modified
	  mode-line-buffer-identification
	  "   "
	  global-mode-string
	  "   %[("
	  mode-name
	  mode-line-process
	  minor-mode-alist
	  "%n"
	  ")%]-"
	  idlwave-shell-mode-line-info
	  "---"
	  (line-number-mode "L%l--")
	  (column-number-mode "C%c--")
	  (-3 . "%p")
	  "-%-"))
850 851 852 853 854 855
  ;; (make-local-variable 'idlwave-shell-bp-alist)
  (setq idlwave-shell-halt-frame nil
        idlwave-shell-trace-frame nil
        idlwave-shell-command-output nil
        idlwave-shell-step-frame nil)
  (idlwave-shell-display-line nil)
856
  (setq idlwave-shell-calling-stack-index 0)
857

858 859 860 861 862
  (when idlwave-shell-query-for-class
      (add-to-list (make-local-variable 'idlwave-determine-class-special)
		   'idlwave-shell-get-object-class)
      (setq idlwave-store-inquired-class t))

863 864 865
  ;; Make sure comint-last-input-end does not go to beginning of
  ;; buffer (in case there were other processes already in this buffer).
  (set-marker comint-last-input-end (point))
866
  (setq idlwave-idlwave_routine_info-compiled nil)
867
  (setq idlwave-shell-ready nil)
868
  (setq idlwave-shell-wait-for-output nil)
869 870 871 872
  (setq idlwave-shell-bp-alist nil)
  (idlwave-shell-update-bp-overlays) ; Throw away old overlays
  (setq idlwave-shell-sources-alist nil)
  (setq idlwave-shell-default-directory default-directory)
873
  (setq idlwave-shell-hide-output nil)
874 875 876

  ;; NB: `make-local-hook' needed for older/alternative Emacs compatibility
  (make-local-hook 'kill-buffer-hook)
877 878
  (add-hook 'kill-buffer-hook 'idlwave-shell-kill-shell-buffer-confirm
	    nil 'local)
879 880
  (add-hook 'kill-buffer-hook 'idlwave-shell-delete-temp-files nil 'local)
  (add-hook 'kill-emacs-hook 'idlwave-shell-delete-temp-files)
881 882
  (use-local-map idlwave-shell-mode-map)
  (easy-menu-add idlwave-shell-mode-menu idlwave-shell-mode-map)
883

884 885 886 887 888
  ;; Set the optional comint variables
  (when idlwave-shell-comint-settings
    (let ((list idlwave-shell-comint-settings) entry)
      (while (setq entry (pop list))
	(set (make-local-variable (car entry)) (cdr entry)))))
889

890 891 892
  ;; IDLWAVE syntax, and turn on abbreviations
  (setq local-abbrev-table idlwave-mode-abbrev-table)
  (set-syntax-table idlwave-mode-syntax-table)
893
  (set (make-local-variable 'comment-start) ";")
894
  (setq abbrev-mode t)
895 896 897

  ;; NB: `make-local-hook' needed for older/alternative Emacs compatibility
  (make-local-hook 'post-command-hook)
898 899
  (add-hook 'post-command-hook 'idlwave-command-hook nil t)

900 901 902 903 904 905 906 907
  ;; Read the command history?
  (when (and idlwave-shell-save-command-history
	     (stringp idlwave-shell-command-history-file))
    (set (make-local-variable 'comint-input-ring-file-name)
	 idlwave-shell-command-history-file)
    (if (file-regular-p idlwave-shell-command-history-file)
	(comint-read-input-ring)))

908
  ;; Run the hooks.
909 910
  (run-hooks 'idlwave-shell-mode-hook)
  (idlwave-shell-send-command idlwave-shell-initial-commands nil 'hide)
911
  ;; Define a system variable which knows the version of IDLWAVE
912
  (idlwave-shell-send-command
913 914 915 916 917 918 919 920 921 922 923 924 925 926 927
   (format "defsysv,'!idlwave_version','%s',1" idlwave-mode-version)
   nil 'hide)
  (if (and (not idlwave-path-alist)
	   (not idlwave-sys-dir))
      (idlwave-shell-send-command idlwave-shell-path-query
				  'idlwave-shell-get-path-info
				  'hide)))

(defun idlwave-shell-get-path-info ()
  (let* ((rpl (idlwave-shell-path-filter))
	 (sysdir (car rpl))
	 (dirs (cdr rpl)))
    (setq idlwave-sys-dir sysdir)
    (setq idlwave-path-alist (mapcar (lambda(x) (cons x nil))
				     dirs))))
928 929 930 931 932 933 934 935 936 937

(if (not (fboundp 'idl-shell))
    (fset 'idl-shell 'idlwave-shell))

(defvar idlwave-shell-idl-wframe nil
  "Frame for displaying the idl shell window.")
(defvar idlwave-shell-display-wframe nil
  "Frame for displaying the idl source files.")

(defvar idlwave-shell-calling-stack-index 0)
938
(defvar idlwave-shell-calling-stack-routine nil)
939 940 941 942 943 944 945 946 947

(defun idlwave-shell-source-frame ()
  "Return the frame to be used for source display."
  (if idlwave-shell-use-dedicated-frame
      ;; We want separate frames for source and shell
      (if (frame-live-p idlwave-shell-display-wframe)
	  ;; The frame exists, so we use it.
	  idlwave-shell-display-wframe
	;; The frame does not exist.  We use the current frame.
948 949
	;; However, if the current is the shell frame, we make a new frame,
	;; or recycle the first existing visible frame
950 951
	(setq idlwave-shell-display-wframe
	      (if (eq (selected-frame) idlwave-shell-idl-wframe)
952 953 954 955 956
		  (or
		   (let ((flist (visible-frame-list))
			 (frame (selected-frame)))
		     (catch 'exit
		       (while flist
957 958
			 (if (not (eq (car flist)
				      idlwave-shell-idl-wframe))
959 960 961
			     (throw 'exit (car flist))
			   (setq flist (cdr flist))))))
		   (make-frame))
962 963 964 965 966 967 968 969 970 971 972 973 974 975
		(selected-frame))))))

(defun idlwave-shell-shell-frame ()
  "Return the frame to be used for the shell buffer."
  (if idlwave-shell-use-dedicated-frame
      ;; We want a dedicated frame
      (if (frame-live-p idlwave-shell-idl-wframe)
	  ;; It does exist, so we use it.
	  idlwave-shell-idl-wframe
	;; It does not exist.  Check if we have a source frame.
	(if (not (frame-live-p idlwave-shell-display-wframe))
	    ;; We do not have a source frame, so we use this one.
	    (setq idlwave-shell-display-wframe (selected-frame)))
	;; Return a new frame
976
	(setq idlwave-shell-idl-wframe
977
	      (make-frame idlwave-shell-frame-parameters)))))
978

979
;;;###autoload
980
(defun idlwave-shell (&optional arg quick)
981 982 983 984 985 986 987 988
  "Run an inferior IDL, with I/O through buffer `(idlwave-shell-buffer)'.
If buffer exists but shell process is not running, start new IDL.
If buffer exists and shell process is running, just switch to the buffer.

When called with a prefix ARG, or when `idlwave-shell-use-dedicated-frame'
is non-nil, the shell buffer and the source buffers will be in
separate frames.

989 990
The command to run comes from variable `idlwave-shell-explicit-file-name',
with options taken from `idlwave-shell-command-line-options'.
991 992 993 994 995 996 997

The buffer is put in `idlwave-shell-mode', providing commands for sending
input and controlling the IDL job.  See help on `idlwave-shell-mode'.
See also the variable `idlwave-shell-prompt-pattern'.

\(Type \\[describe-mode] in the shell buffer for a list of commands.)"
  (interactive "P")
998 999 1000 1001 1002 1003 1004
  (if (eq arg 'quick)
      (progn
	(let ((idlwave-shell-use-dedicated-frame nil))
	  (idlwave-shell nil)
	  (delete-other-windows))
	(and idlwave-shell-use-dedicated-frame
	     (setq idlwave-shell-idl-wframe (selected-frame)))
1005
	(add-hook 'idlwave-shell-sentinel-hook
1006 1007 1008 1009 1010 1011
		  'save-buffers-kill-emacs t))

    ;; A non-nil arg means, we want a dedicated frame.  This will last
    ;; for the current editing session.
    (if arg (setq idlwave-shell-use-dedicated-frame t))
    (if (equal arg '(16)) (setq idlwave-shell-use-dedicated-frame nil))
1012

1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
    ;; Check if the process still exists.  If not, create it.
    (unless (comint-check-proc (idlwave-shell-buffer))
      (let* ((prg (or idlwave-shell-explicit-file-name "idl"))
	     (buf (apply 'make-comint
			 idlwave-shell-process-name prg nil
			 (if (stringp idlwave-shell-command-line-options)
			     (idlwave-split-string
			      idlwave-shell-command-line-options)
			   idlwave-shell-command-line-options)))
	     (process (get-buffer-process buf)))
	(setq idlwave-idlwave_routine_info-compiled nil)
	(set-process-filter process 'idlwave-shell-filter)
	(set-process-sentinel process 'idlwave-shell-sentinel)
	(set-buffer buf)
	(idlwave-shell-mode)))
    (let ((window (idlwave-display-buffer (idlwave-shell-buffer) nil
					  (idlwave-shell-shell-frame)))
	  (current-window (selected-window)))
      (select-window window)
      (goto-char (point-max))
      (select-window current-window)
      (if idlwave-shell-ready
	  (raise-frame (window-frame window)))
      (if (eq (selected-frame) (window-frame window))
	  (select-window window))
      )))
1039 1040 1041 1042 1043 1044 1045 1046

(defun idlwave-shell-recenter-shell-window (&optional arg)
  "Run `idlwave-shell', but make sure the current window stays selected."
  (interactive "P")
  (let ((window (selected-window)))
    (idlwave-shell arg)
    (select-window window)))

1047 1048 1049 1050 1051 1052
(defun idlwave-shell-hide-p (type)
  "Whether to hide this type of command.
Return either nil or 'hide."
  (if (listp idlwave-shell-show-commands)
      (if (not (memq type idlwave-shell-show-commands)) 'hide)))

1053 1054 1055
(defun idlwave-shell-send-command (&optional cmd pcmd hide preempt)
  "Send a command to IDL process.

1056 1057 1058 1059 1060 1061
\(CMD PCMD HIDE\) are placed at the end of
` idlwave-shell-pending-commands'.  If IDL is ready the first command,
CMD, in `idlwave-shell-pending-commands' is sent to the IDL process.
If optional second argument PCMD is non-nil it will be placed on
`idlwave-shell-post-command-hook' when CMD is executed.  If the
optional third argument HIDE is non-nil, then hide output from CMD.
1062
If optional fourth argument PREEMPT is non-nil CMD is put at front of
1063 1064 1065 1066 1067 1068
`idlwave-shell-pending-commands'.  If PREEMPT is 'wait, wait for all
output to complete and the next prompt to arrive before returning
\(useful if you need an answer now\). IDL is considered ready if the
prompt is present and if `idlwave-shell-ready' is non-nil."

;  (setq hide nil)  ;  FIXME: turn this on for debugging only
1069
;  (if (null cmd)
1070
;      (progn
1071
;	(message "SENDING Pending commands: %s"
1072 1073
;		 (prin1-to-string idlwave-shell-pending-commands)))
;    (message "SENDING %s|||%s" cmd pcmd))
1074
  (if (and (symbolp idlwave-shell-show-commands)
1075 1076 1077 1078
	   (eq idlwave-shell-show-commands 'everything))
      (setq hide nil))
  (let ((save-buffer (current-buffer))
	buf proc)
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
    ;; Get or make the buffer and its process
    (if (or (not (setq buf (get-buffer (idlwave-shell-buffer))))
	    (not (setq proc (get-buffer-process buf))))
	(if (not idlwave-shell-automatic-start)
	    (error
	     (substitute-command-keys
	      "You need to first start an IDL shell with \\[idlwave-shell]"))
	  (idlwave-shell-recenter-shell-window)
	  (setq buf (get-buffer (idlwave-shell-buffer)))
	  (if (or (not (setq buf (get-buffer (idlwave-shell-buffer))))
		  (not (setq proc (get-buffer-process buf))))
	      ;; Still nothing
	      (error "Problem with autostarting IDL shell"))))
1092
    (when (or cmd idlwave-shell-pending-commands)
1093 1094 1095
      (set-buffer buf)
      ;; To make this easy, always push CMD onto pending commands
      (if cmd
1096 1097 1098 1099 1100 1101
	  (setq idlwave-shell-pending-commands
		(if preempt
		    ;; Put at front.
		    (append (list (list cmd pcmd hide))
			    idlwave-shell-pending-commands)
		  ;; Put at end.
1102
		  (append idlwave-shell-pending-commands
1103
			  (list (list cmd pcmd hide))))))
1104
      ;; Check if IDL ready
1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
      (let ((save-point (point-marker)))
	(goto-char (process-mark proc))
	(if (and idlwave-shell-ready
		 ;; Check for IDL prompt
		 (prog2
		   (forward-line 0)
		   ;; (beginning-of-line) ; Changed for Emacs 21
		   (looking-at idlwave-shell-prompt-pattern)
		   (goto-char (process-mark proc))))
	    ;; IDL ready for command, execute it
	    (let* ((lcmd (car idlwave-shell-pending-commands))
		   (cmd (car lcmd))
		   (pcmd (nth 1 lcmd))
		   (hide (nth 2 lcmd)))
	      ;; If this is an executive command, reset the stack pointer
	      (if (eq (string-to-char cmd) ?.)
		  (setq idlwave-shell-calling-stack-index 0))
	      ;; Set post-command
	      (setq idlwave-shell-post-command-hook pcmd)
	      ;; Output hiding
	      (setq idlwave-shell-hide-output hide)
	      ;; Pop command
	      (setq idlwave-shell-pending-commands
		    (cdr idlwave-shell-pending-commands))
	      ;; Send command for execution
	      (set-marker comint-last-input-start (point))
	      (set-marker comint-last-input-end (point))
	      (comint-simple-send proc cmd)
	      (setq idlwave-shell-ready nil)
	      (when (equal preempt 'wait) ; Get all the output at once
		(setq idlwave-shell-wait-for-output t)
		(accept-process-output proc))))
	(goto-char save-point))
      (set-buffer save-buffer))))
1139

1140 1141 1142 1143 1144 1145 1146 1147
(defun idlwave-shell-send-char (c &optional no-error)
  "Send one character to the shell, without a newline."
  (interactive "cChar to send to IDL: ")
  (let ((errf (if (interactive-p) 'error 'message))
	buf proc)
    (if (or (not (setq buf (get-buffer (idlwave-shell-buffer))))
	    (not (setq proc (get-buffer-process buf))))
	(funcall errf "Shell is not running"))
1148
    (if (equal c ?\C-g)
1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
	(funcall errf "Abort")
      (comint-send-string proc (char-to-string c)))))

(defvar idlwave-shell-char-mode-active)
(defun idlwave-shell-input-mode-magic (string)
  "Check STRING for magic words and toggle character input mode.
See also the variable `idlwave-shell-input-mode-spells'."
  (cond
   ((string-match (car idlwave-shell-input-mode-spells) string)
    (call-interactively 'idlwave-shell-send-char))
   ((and (boundp 'idlwave-shell-char-mode-active)
	 (string-match (nth 2 idlwave-shell-input-mode-spells) string))
    (setq idlwave-shell-char-mode-active 'exit))
   ((string-match (nth 1 idlwave-shell-input-mode-spells) string)
    ;; Set a timer which will soon start the character loop
    (if (fboundp 'start-itimer)
	(start-itimer "IDLWAVE Char Mode" 'idlwave-shell-char-mode-loop 0.5
		      nil nil t 'no-error)
      (run-at-time 0.5 nil 'idlwave-shell-char-mode-loop 'no-error)))))

(defvar keyboard-quit)
(defun idlwave-shell-char-mode-loop (&optional no-error)
  "Enter a loop which accepts single characters and sends them to IDL.
Characters are sent one by one, without newlines.  The loop is blocking
and intercepts all input events to Emacs.  You can use this command
to interact with the IDL command GET_KBRD.
The loop can be aborted by typing `C-g'.  The loop also exits automatically
when the IDL prompt gets displayed again after the current IDL command."
  (interactive)

  ;; First check if there is a shell waiting for input
  (let ((idlwave-shell-char-mode-active t)
	(errf (if no-error 'message 'error))
	buf proc c)
    (if (or (not (setq buf (get-buffer (idlwave-shell-buffer))))
	    (not (setq proc (get-buffer-process buf))))
	(funcall errf "Shell is not running"))
    (if idlwave-shell-ready
	(funcall errf "No IDL program seems to be waiting for input"))

1189
    ;; OK, start the loop
1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205
    (message "Character mode on:  Sending single chars (`C-g' to exit)")
    (message
     (catch 'exit
       (while t
	 ;; Wait for input
	 ;; FIXME: Is it too dangerous to inhibit quit here?
	 (let ((inhibit-quit t))
	   ;; We wait and check frequently if we should abort
	   (while (sit-for 0.3)
	     (and idlwave-shell-ready
		  (throw 'exit "Character mode off (prompt displayed)"))
	     (and (eq idlwave-shell-char-mode-active 'exit)
		  (throw 'exit "Character mode off (closing spell incantation)")))
	   ;; Interpret input as a character - ignore non-char input
	   (condition-case nil
	       (setq c (read-char))
1206
	     (error (ding) (throw 'exit "Character mode off")))
1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218
	   (cond
	    ((null c)               ; Non-char event: ignore
	     (ding))
	    ((equal c ?\C-g)        ; Abort the loop
	     (setq keyboard-quit nil)
	     (ding)
	     (throw 'exit "Character mode off (keyboard quit)"))
	    (t	                   ; Send the character and continue the loop
	     (comint-send-string proc (char-to-string c))))
	   (and (eq idlwave-shell-char-mode-active 'exit)
		(throw 'exit "Single char loop exited"))))))))

1219
(defun idlwave-shell-move-or-history (up &optional arg)
1220
  "When in last line of process buffer, do `comint-previous-input'.
1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237
Otherwise just move the line.  Move down unless UP is non-nil."
  (let* ((proc-pos (marker-position
		    (process-mark (get-buffer-process (current-buffer)))))
	 (arg (or arg 1))
	 (arg (if up arg (- arg))))
    (if (eq t idlwave-shell-arrows-do-history) (goto-char proc-pos))
    (if (and idlwave-shell-arrows-do-history
	     (>= (1+ (save-excursion (end-of-line) (point))) proc-pos))
	(progn
	  (goto-char proc-pos)
	  (and (not (eolp)) (kill-line nil))
	  (comint-previous-input arg))
      (previous-line arg))))

(defun idlwave-shell-up-or-history (&optional arg)
"When in last line of process buffer, move to previous input.
 Otherwise just go up one line."
1238
  (interactive "p")
1239
  (idlwave-shell-move-or-history t arg))
1240 1241

(defun idlwave-shell-down-or-history (&optional arg)
1242 1243
"When in last line of process buffer, move to next input.
 Otherwise just go down one line."
1244
  (interactive "p")
1245
  (idlwave-shell-move-or-history nil arg))
1246

1247 1248
;; Newer versions of comint.el changed the name of comint-filter to
;; comint-output-filter.
1249 1250 1251 1252 1253 1254 1255 1256 1257
(defun idlwave-shell-comint-filter (process string) nil)
(if (fboundp 'comint-output-filter)
    (fset 'idlwave-shell-comint-filter (symbol-function 'comint-output-filter))
  (fset 'idlwave-shell-comint-filter (symbol-function 'comint-filter)))

(defun idlwave-shell-is-running ()
  "Return t if the shell process is running."
  (eq (process-status idlwave-shell-process-name) 'run))

1258 1259
(defvar idlwave-shell-hidden-output-buffer " *idlwave-shell-hidden-output*"
  "Buffer containing hidden output from IDL commands.")
1260

1261 1262 1263 1264 1265 1266 1267
(defun idlwave-shell-filter (proc string)
  "Replace Carriage returns in output. Watch for prompt.
When the IDL prompt is received executes `idlwave-shell-post-command-hook'
and then calls `idlwave-shell-send-command' for any pending commands."
  ;; We no longer do the cleanup here - this is done by the process sentinel
  (when (eq (process-status idlwave-shell-process-name) 'run)
    ;; OK, process is still running, so we can use it.
1268
    (let ((data (match-data)) p)
1269 1270 1271
      (unwind-protect
          (progn
            ;; May change the original match data.
1272 1273 1274
	    (while (setq p (string-match "\C-M" string))
	      (aset string p ?\  ))

1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285
            ;;
            ;; Keep output

; Should not keep output because the concat is costly.  If hidden put
; the output in a hide-buffer.  Then when the output is needed in post
; processing can access either the hide buffer or the idlwave-shell
; buffer.  Then watching for the prompt is easier.  Furthermore, if it
; is hidden and there is no post command, could throw away output.
;           (setq idlwave-shell-command-output
;                 (concat idlwave-shell-command-output string))
            ;; Insert the string. Do this before getting the
1286
            ;; state.
1287 1288 1289
	    (while (setq p (string-match "\C-G" string))
	      (ding)
	      (aset string p ?\C-j ))
1290 1291 1292
            (if idlwave-shell-hide-output
                (save-excursion
                  (set-buffer
1293
                   (get-buffer-create idlwave-shell-hidden-output-buffer))
1294 1295
                  (goto-char (point-max))
                  (insert string))
1296
	      (idlwave-shell-comint-filter proc string))
1297
            ;; Watch for magic - need to accumulate the current line