Initial Commit
[packages] / xemacs-packages / idlwave / idlwave.el
1 ;; idlwave.el --- IDL editing mode for GNU Emacs
2 ;; Copyright (c) 1999, 2000, 2001, 2002, 2003 Free Software Foundation
3
4 ;; Authors: J.D. Smith <jdsmith@as.arizona.edu>
5 ;;          Carsten Dominik <dominik@astro.uva.nl>
6 ;;          Chris Chase <chase@att.com>
7 ;; Maintainer: J.D. Smith <jdsmith@as.arizona.edu>
8 ;; Version: 5.1
9 ;; Date: $Date: 2003-08-12 12:26:18 $
10 ;; Keywords: languages
11
12 ;; This file is part of GNU Emacs.
13
14 ;; GNU Emacs is free software; you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation; either version 2, or (at your option)
17 ;; any later version.
18
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22 ;; GNU General Public License for more details.
23
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
26 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
27 ;; Boston, MA 02111-1307, USA.
28
29 ;;; Commentary:
30
31 ;; In remotely distant past, based on pascal.el, though bears little
32 ;; resemblance to it now.
33 ;;
34 ;; Incorporates many ideas, such as abbrevs, action routines, and
35 ;; continuation line indenting, from wave.el.
36 ;; wave.el original written by Lubos Pochman, Precision Visuals, Boulder.
37 ;;
38 ;; See the mode description ("C-h m" in idlwave-mode or "C-h f idlwave-mode")
39 ;; for features, key bindings, and info.
40 ;; Also, Info format documentation is available with `M-x idlwave-info'
41 ;;
42 ;; New versions of IDLWAVE, documentation, and more information
43 ;; available from:
44 ;;                 http://idlwave.org
45 ;;
46 ;; INSTALLATION
47 ;; ============
48 ;;
49 ;; Follow the instructions in the INSTALL file of the distribution.
50 ;; In short, put this file on your load path and add the following
51 ;; lines to your .emacs file:
52 ;;
53 ;; (autoload 'idlwave-mode "idlwave" "IDLWAVE Mode" t)
54 ;; (autoload 'idlwave-shel "idlw-shell" "IDLWAVE Shell" t)
55 ;; (setq auto-mode-alist (cons '("\\.pro\\'" . idlwave-mode) auto-mode-alist))
56 ;;
57 ;;
58 ;; SOURCE
59 ;; ======
60 ;;
61 ;; The newest version of this file is available from the maintainer's
62 ;; Webpage:
63 ;;
64 ;;   http://idlwave.org
65 ;;
66 ;; DOCUMENTATION
67 ;; =============
68 ;;
69 ;; IDLWAVE is documented online in info format.  A printable version
70 ;; of the documentation is available from the maintainers webpage (see
71 ;; SOURCE).
72 ;;
73 ;; 
74 ;; ACKNOWLEDGMENTS
75 ;; ===============
76 ;;
77 ;;  Thanks to the following people for their contributions and comments:
78 ;;
79 ;;    Ulrik Dickow <dickow@nbi.dk>
80 ;;    Eric E. Dors <edors@lanl.gov>
81 ;;    Stein Vidar H. Haugan <s.v.h.haugan@astro.uio.no>
82 ;;    David Huenemoerder <dph@space.mit.edu>
83 ;;    Kevin Ivory <Kevin.Ivory@linmpi.mpg.de>
84 ;;    Dick Jackson <dick@d-jackson.com>
85 ;;    Xuyong Liu <liu@stsci.edu>
86 ;;    Simon Marshall <Simon.Marshall@esrin.esa.it>
87 ;;    Laurent Mugnier <mugnier@onera.fr>
88 ;;    Lubos Pochman <lubos@rsinc.com>
89 ;;    Bob Portmann <portmann@al.noaa.gov>
90 ;;    Patrick M. Ryan <pat@jaameri.gsfc.nasa.gov>
91 ;;    Marty Ryba <ryba@ll.mit.edu>
92 ;;    Phil Williams <williams@irc.chmcc.org>
93 ;;    Phil Sterne <sterne@dublin.llnl.gov>
94 ;;
95 ;; CUSTOMIZATION:
96 ;; =============
97 ;;
98 ;; IDLWAVE has extensive customize support; to learn about the
99 ;; variables which control the mode's behavior, use `M-x
100 ;; idlwave-customize'.
101 ;;
102 ;; You can set your own preferred values with Customize, or with Lisp
103 ;; code in .emacs.  For an example of what to put into .emacs, check
104 ;; the TexInfo documentation or see a complete .emacs available at the
105 ;; website.
106 ;;
107 ;; KNOWN PROBLEMS:
108 ;; ==============
109 ;;
110 ;;   IDLWAVE support for the IDL-derived PV-WAVE CL language of Visual
111 ;;   Numerics, Inc. is growing less and less complete as the two
112 ;;   languages grow increasingly apart.  The mode probably shouldn't
113 ;;   even have "WAVE" in it's title, but it's catchy, and was required
114 ;;   to avoid conflict with the CORBA idl.el mode.  Caveat WAVEor.
115 ;;
116 ;;   Moving the point backwards in conjunction with abbrev expansion
117 ;;   does not work as I would like it, but this is a problem with
118 ;;   emacs abbrev expansion done by the self-insert-command.  It ends
119 ;;   up inserting the character that expanded the abbrev after moving
120 ;;   point backward, e.g., "\cl" expanded with a space becomes
121 ;;   "LONG( )" with point before the close paren.  This is solved by
122 ;;   using a temporary function in `post-command-hook' - not pretty, 
123 ;;   but it works.
124 ;;
125 ;;   Tabs and spaces are treated equally as whitespace when filling a
126 ;;   comment paragraph.  To accomplish this, tabs are permanently
127 ;;   replaced by spaces in the text surrounding the paragraph, which
128 ;;   may be an undesirable side-effect.  Replacing tabs with spaces is
129 ;;   limited to comments only and occurs only when a comment
130 ;;   paragraph is filled via `idlwave-fill-paragraph'.
131 ;;
132 ;;   Muti-statement lines (using "&") on block begin and end lines can
133 ;;   ruin the formatting.  For example, multiple end statements on a
134 ;;   line: endif & endif.  Using "&" outside of block begin/end lines
135 ;;   should be okay.
136 ;;
137 ;;   Determining the expression at point for printing and other
138 ;;   examination commands is somewhat rough: currently only fairly
139 ;;   simple entities are found.  You can always drag-select or examine
140 ;;   a pre-selected region.
141 ;;
142 ;;   When forcing completion of method keywords, the initial
143 ;;   query for a method has multiple entries for some methods.  Would
144 ;;   be too difficult to fix this hardly used case.
145 ;;
146 \f
147 ;;; Code:
148
149
150 (eval-when-compile (require 'cl))
151 (require 'idlw-help)
152
153 ;; For XEmacs
154 (unless (fboundp 'line-beginning-position)
155   (defalias 'line-beginning-position 'point-at-bol))
156 (unless (fboundp 'line-end-position)
157   (defalias 'line-end-position 'point-at-eol))
158
159 (eval-and-compile
160   ;; Kludge to allow `defcustom' for Emacs 19.
161   (condition-case () (require 'custom) (error nil))
162   (if (and (featurep 'custom) (fboundp 'custom-declare-variable))
163       nil ;; We've got what we needed
164     ;; We have the old or no custom-library, hack around it!
165     (defmacro defgroup (&rest args) nil)
166     (defmacro defcustom (var value doc &rest args) 
167       `(defvar ,var ,value ,doc))))
168
169 (defgroup idlwave nil
170   "Major mode for editing IDL .pro files"
171   :tag "IDLWAVE"
172   :link '(url-link :tag "Home Page" 
173                    "http://idlwave.org")
174   :link '(emacs-commentary-link :tag "Commentary in idlw-shell.el"
175                                 "idlw-shell.el")
176   :link '(emacs-commentary-link :tag "Commentary in idlwave.el" "idlwave.el")
177   :link '(custom-manual "(idlwave)Top")
178   :prefix "idlwave"
179   :group 'languages)
180
181
182 ;;; Variables for indentation behavior ---------------------------------------
183
184 (defgroup idlwave-code-formatting nil
185   "Indentation and formatting options for IDLWAVE mode."
186   :group 'idlwave)
187
188 (defcustom idlwave-main-block-indent 0
189   "*Extra indentation for the main block of code.
190 That is the block between the FUNCTION/PRO statement and the END
191 statement for that program unit."
192   :group 'idlwave-code-formatting
193   :type 'integer)
194
195 (defcustom idlwave-block-indent 4
196   "*Extra indentation applied to block lines.
197 If you change this, you probably also want to change `idlwave-end-offset'."
198   :group 'idlwave-code-formatting
199   :type 'integer)
200
201 (defcustom idlwave-end-offset -4
202   "*Extra indentation applied to block END lines.
203 A value equal to negative `idlwave-block-indent' will make END lines
204 line up with the block BEGIN lines."
205   :group 'idlwave-code-formatting
206   :type 'integer)
207
208 (defcustom idlwave-continuation-indent 2
209   "*Extra indentation applied to continuation lines.
210 This extra offset applies to the first of a set of continuation lines.
211 The following lines receive the same indentation as the first."
212   :group 'idlwave-code-formatting
213   :type 'integer)
214
215 (defcustom idlwave-max-extra-continuation-indent 20
216   "*Maximum additional indentation for special continuation indent.
217 Several special indentations are tried to help line up continuation
218 lines in routine calls or definitions, other statements with
219 parentheses, or assignment statements.  This variable specifies a
220 maximum amount by which this special indentation can exceed the
221 standard continuation indentation, otherwise defaulting to a fixed
222 offset.  Set to 0 to effectively disable all special continuation
223 indentation, or to a large number (like 100) to enable it in all
224 cases.  See also `idlwave-indent-top-open-paren', which can override
225 this variable."
226   :group 'idlwave-code-formatting
227   :type 'integer)
228
229 (defcustom idlwave-indent-to-open-paren t
230   "*Non-nil means, indent continuation lines to innermost open
231 parenthesis.  This indentation occurs even if otherwise disallowed by
232 `idlwave-max-extra-continuation-indent'.  Matching parens and the
233 interleaving args are lined up.  Example:
234
235   x = function_a(function_b(function_c( a, b, [1,2,3, $
236                                                4,5,6 $
237                                               ], $
238                                         c, d $
239                                       )))
240
241 When this variable is nil, paren alignment may still occur, based on
242 the value of `max-extra-continuation-indent', which, if zero, would
243 yield:
244
245   x = function_a(function_b(function_c( a, b, [1,2,3, $
246      4,5,6 $
247      ], $
248      c, d $
249      )))"
250  :group 'idlwave-code-formatting
251   :type 'boolean)
252
253 (defcustom idlwave-hanging-indent t
254   "*If set non-nil then comment paragraphs are indented under the
255 hanging indent given by `idlwave-hang-indent-regexp' match in the first line
256 of the paragraph."
257   :group 'idlwave-code-formatting
258   :type 'boolean)
259
260 (defcustom idlwave-hang-indent-regexp "- "
261   "*Regular expression matching the position of the hanging indent
262 in the first line of a comment paragraph. The size of the indent
263 extends to the end of the match for the regular expression."
264   :group 'idlwave-code-formatting
265   :type 'regexp)
266
267 (defcustom idlwave-use-last-hang-indent nil
268   "*If non-nil then use last match on line for `idlwave-indent-regexp'."
269   :group 'idlwave-code-formatting
270   :type 'boolean)
271
272 (defcustom idlwave-fill-comment-line-only t
273   "*If non-nil then auto fill will only operate on comment lines."
274   :group 'idlwave-code-formatting
275   :type 'boolean)
276
277 (defcustom idlwave-auto-fill-split-string t
278   "*If non-nil then auto fill will split strings with the IDL `+' operator.
279 When the line end falls within a string, string concatenation with the 
280 '+' operator will be used to distribute a long string over lines.  
281 If nil and a string is split then a terminal beep and warning are issued.
282
283 This variable is ignored when `idlwave-fill-comment-line-only' is
284 non-nil, since in this case code is not auto-filled."
285   :group 'idlwave-code-formatting
286   :type 'boolean)
287
288 (defcustom idlwave-split-line-string t
289   "*If non-nil then `idlwave-split-line' will split strings with `+'.
290 When the splitting point of a line falls inside a string, split the string
291 using the `+' string concatenation operator.  If nil and a string is
292 split then a terminal beep and warning are issued."
293   :group 'idlwave-code-formatting
294   :type 'boolean)
295
296 (defcustom idlwave-no-change-comment ";;;"
297   "*The indentation of a comment that starts with this regular
298 expression will not be changed. Note that the indentation of a comment
299 at the beginning of a line is never changed."
300   :group 'idlwave-code-formatting
301   :type 'string)
302
303 (defcustom idlwave-begin-line-comment nil
304   "*A comment anchored at the beginning of line.
305 A comment matching this regular expression will not have its
306 indentation changed.  If nil the default is \"^;\", i.e., any line
307 beginning with a \";\".  Expressions for comments at the beginning of
308 the line should begin with \"^\"."
309   :group 'idlwave-code-formatting
310   :type '(choice (const :tag "Any line beginning with `;'" nil)
311                  'regexp))
312
313 (defcustom idlwave-code-comment ";;[^;]"
314   "*A comment that starts with this regular expression on a line by
315 itself is indented as if it is a part of IDL code.  As a result if
316 the comment is not preceded by whitespace it is unchanged."
317   :group 'idlwave-code-formatting
318   :type 'regexp)
319
320 ;; Comments not matching any of the above will be indented as a
321 ;; right-margin comment, i.e., to a minimum of `comment-column'.
322
323 ;;; Routine Info and Completion ---------------------------------------
324
325 (defgroup idlwave-routine-info nil
326   "Routine Info options for IDLWAVE mode."
327   :group 'idlwave)
328
329 (defcustom idlwave-use-library-catalogs t
330   "*Non-nil means search the IDL path for library catalog files.
331
332 These files, named .idlwave_catalog, document routine information for
333 individual directories and libraries of IDL .pro files.  Many popular
334 libraries come with catalog files by default, so leaving this on is a
335 usually a good idea.."
336   :group 'idlwave-routine-info
337   :type 'boolean)
338
339 (defcustom idlwave-init-rinfo-when-idle-after 10
340   "*Seconds of idle time before routine info is automatically initialized.
341 Initializing the routine info can take long, in particular if a large
342 library catalog is involved.  When Emacs is idle for more than the number
343 of seconds specified by this variable, it starts the initialization.
344 The process is split into five steps, in order to keep possible work 
345 interruption as short as possible.  If one of the steps finishes, and no
346 user input has arrived in the mean time, initialization proceeds immediately
347 to the next step.
348 A good value for this variable is about 1/3 of the time initialization
349 take in you setup.  So if you have a fast machine and no problems with a slow network connection, don't hesitate to set this to 2 seconds.
350 A Value of 0 means, don't initialize automatically."
351   :group 'idlwave-routine-info
352   :type 'number)
353
354 (defcustom idlwave-scan-all-buffers-for-routine-info t
355   "*Non-nil means, scan buffers for IDL programs when updating info.
356 The scanning is done by the command `idlwave-update-routine-info'.
357 The following values are allowed:
358
359 nil       Don't scan any buffers.
360 t         Scan all idlwave-mode buffers in the current editing session.
361 current   Scan only the current buffer, but no other buffers."
362   :group 'idlwave-routine-info
363   :type '(choice
364           (const :tag "No buffer" nil)
365           (const :tag "All buffers" t)
366           (const :tag "Current buffer only" 'current)))
367
368 (defcustom idlwave-query-shell-for-routine-info t
369   "*Non-nil means query the shell for info about compiled routines.
370 Querying the shell is useful to get information about compiled modules,
371 and it is turned on by default.  However, when you have a complete library
372 scan, this is not necessary."
373   :group 'idlwave-routine-info
374   :type 'boolean)
375
376 (defcustom idlwave-auto-routine-info-updates
377   '(find-file save-buffer kill-buffer compile-buffer)
378   "*Controls under what circumstances routine info is updated automatically.
379 Possible values:
380 nil       Never
381 t         All available
382 \(...)     A list of circumstances. Allowed members are:
383            find-file       Add info for new IDLWAVE buffers.
384            save-buffer     Update buffer info when buffer is saved
385            kill-buffer     Remove buffer info when buffer gets killed
386            compile-buffer  Update shell info after `idlwave-shell-save-and...'"
387   :group 'idlwave-routine-info
388   :type '(choice
389           (const :tag "Never" nil)
390           (const :tag "As often as possible" t)
391           (set :tag "Checklist" :greedy t
392                (const :tag "When visiting a file" find-file)
393                (const :tag "When saving a buffer" save-buffer)
394                (const :tag "After a buffer was killed" kill-buffer)
395                (const :tag "After a buffer was compiled successfully, update shell info" compile-buffer))))
396                
397 (defcustom idlwave-rinfo-max-source-lines 5
398   "*Maximum number of source files displayed in the Routine Info window.
399 When an integer, it is the maximum number of source files displayed.
400 t means to show all source files."
401   :group 'idlwave-routine-info
402   :type 'integer)
403
404 (defcustom idlwave-library-path nil
405   "Library path for Windows and MacOS.  Not needed under Unix.  When
406 selecting the directories to scan for IDL user catalog routine info,
407 IDLWAVE can, under UNIX, query the shell for the exact search path
408 \(the value of !PATH).  However, under Windows and MacOS (pre-OSX),
409 the IDLWAVE shell does not work.  In this case, this variable can be
410 set to specify the paths where IDLWAVE can find PRO files.  The shell
411 will only be asked for a list of paths when this variable is nil.  The
412 value is a list of directories.  A directory preceeded by a `+' will
413 be searched recursively.  If you set this variable on a UNIX system,
414 the shell will not be queried.  See also `idlwave-system-directory'."
415   :group 'idlwave-routine-info
416   :type '(repeat (directory)))
417
418 (defcustom idlwave-system-directory ""
419   "The IDL system directory for Windows and MacOS.  Not needed under
420 UNIX.  Set this to the value of the `!DIR' system variable in IDL.
421 IDLWAVE uses this to find out which of the library routines belong to
422 the official system library.  All files inside the `lib' subdirectory
423 are considered system library files - so don't install private stuff
424 in this directory.  On UNIX systems, IDLWAVE queries the shell for the
425 value of `!DIR'.  See also `idlwave-library-path'."
426   :group 'idlwave-routine-info
427   :type 'directory)
428
429 (defcustom idlwave-config-directory 
430   (convert-standard-filename "~/.idlwave")
431   "*Directory for configuration files and user-library catalog."
432   :group 'idlwave-routine-info
433   :type 'file)
434
435 (defvar idlwave-user-catalog-file "idlusercat.el")
436 (defvar idlwave-path-file "idlpath.el")
437
438 (defvar idlwave-libinfo-file nil
439   "*Obsolete variable, no longer used.")
440
441 (defcustom idlwave-special-lib-alist nil
442   "Alist of regular expressions matching special library directories.
443 When listing routine source locations, IDLWAVE gives a short hint where
444 the file defining the routine is located.  By default it lists `SystemLib' 
445 for routines in the system library `!DIR/lib' and `Library' for anything
446 else.  This variable can define additional types.  The car of each entry
447 is a regular expression matching the file name (they normally will match
448 on the path).  The cdr is the string to be used as identifier.  Max 10
449 chars are allowed."
450   :group 'idlwave-routine-info
451   :type '(repeat
452           (cons regexp string)))
453
454 (defcustom idlwave-auto-write-paths t
455   "Write out path (!PATH) and system directory (!DIR) info automatically.  
456 Path info is needed to locate library catalog files.  If non-nil,
457 whenever the path-list changes as a result of shell-query, etc., it is
458 written to file.  Otherwise, the menu option \"Write Paths\" can be
459 used to force a write."
460   :group 'idlwave-routine-info
461   :type 'boolean)
462
463 (defgroup idlwave-completion nil
464   "Completion options for IDLWAVE mode."
465   :prefix "idlwave"
466   :group 'idlwave)
467
468 (eval-and-compile
469   (defconst idlwave-tmp
470     '(choice :tag "by applying the function"
471       (const upcase)
472       (const downcase)
473       (const capitalize)
474       (const preserve)
475       (symbol :tag "Other"))))
476
477 (defcustom idlwave-completion-case '((routine . upcase)
478                                      (keyword . upcase)
479                                      (class   . preserve)
480                                      (method  . preserve))
481   "Association list setting the case of completed words.
482
483 This variable determines the case (UPPER/lower/Capitalized...) of
484 words inserted into the buffer by completion.  The preferred case can
485 be specified separately for routine names, keywords, classes and
486 methods. 
487 This alist should therefore have entries for `routine' (normal
488 functions and procedures, i.e. non-methods), `keyword', `class', and
489 `method'.  Plausible values are
490
491 upcase      upcase whole word, like `BOX_CURSOR'
492 downcase    downcase whole word, like `read_ppm'
493 capitalize  capitalize each part, like `Widget_Control'
494 preserve    preserve case as is, like `IDLgrView'
495
496 The value can also be any Emacs Lisp function which transforms the
497 case of characters in a string.
498
499 A value of `preserve' means that the case of the completed word is
500 identical to the way it was written in the definition statement of the
501 routine.  This was implemented to allow for mixed-case completion, in
502 particular of object classes and methods.
503 If a completable word is defined in multiple locations, the meaning of
504 `preserve' is not unique since the different definitions might be
505 cased differently.  Therefore IDLWAVE always takes the case of the
506 *first* definition it encounters during routine info collection and
507 uses the case derived from it consistently.
508
509 Note that a lowercase-only string in the buffer will always be completed in
510 lower case (but see the variable `idlwave-completion-force-default-case').
511
512 After changing this variable, you need to either restart Emacs or press
513 `C-u C-c C-i' to update the internal lists."
514   :group 'idlwave-completion
515   :type `(repeat
516           (cons (symbol :tag "Derive completion case for")
517                 ,idlwave-tmp)))
518
519 (defcustom idlwave-completion-force-default-case nil
520   "*Non-nil means, completion will always honor `idlwave-completion-case'.
521 When nil, only the completion of a mixed case or upper case string
522 will honor the default settings in `idlwave-completion-case', while
523 the completion of lower case strings will be completed entirely in
524 lower case."
525   :group 'idlwave-completion
526   :type 'boolean)
527
528 (defcustom idlwave-complete-empty-string-as-lower-case nil
529   "*Non-nil means, the empty string is considered downcase for completion.
530 The case of what is already in the buffer determines the case of completions.
531 When this variable is non-nil, the empty string is considered to be downcase.
532 Completing on the empty string then offers downcase versions of the possible
533 completions."
534   :group 'idlwave-completion
535   :type 'boolean)
536
537 (defvar idlwave-default-completion-case-is-down nil
538   "Obsolete variable.  See `idlwave-complete-empty-string-as-lower-case' and
539 `idlwave-completion-case'.")
540
541 (defcustom idlwave-buffer-case-takes-precedence nil
542   "*Non-nil means, the case of tokens in buffers dominates over system stuff.
543 To make this possible, we need to re-case everything each time we update
544 the routine info from the buffers.  This is slow.
545 The default is to consider the case given in the system and library files
546 first which makes updating much faster."
547   :group 'idlwave-completion
548   :type 'boolean)
549
550 (defcustom idlwave-highlight-help-links-in-completion t
551   "*Non-nil means, highlight completions for which system help is available.
552 Help can then be accessed with mouse-3.
553 This option is only effective when the online help system is installed."
554   :group 'idlwave-completion
555   :type 'boolean)
556
557 (defcustom idlwave-support-inheritance t
558   "Non-nil means, treat inheritance with completion, online help etc.
559 When nil, IDLWAVE only knows about the native methods and tags of a class,
560 not about inherited ones."
561   :group 'idlwave-routine-info
562   :type 'boolean)
563
564 (defcustom idlwave-keyword-class-inheritance '("^[gs]etproperty$" "^init$")
565   "List of regular expressions for class-driven keyword inheritance.
566 Keyword inheritance is often tied to class inheritance by \"chaining\"
567 up the class tree.  While it cannot be assumed that the presence of an
568 _EXTRA or _REF_EXTRA symbol guarantees such chaining will occur, for
569 certain methods this assumption is almost always true.  The methods
570 for which to assume this can be set here."
571   :group 'idlwave-routine-info
572   :type '(repeat (regexp :tag "Match method:")))
573   
574
575 (defcustom idlwave-completion-show-classes 1
576   "*Number of classes to show when completing object methods and keywords.
577 When completing methods or keywords for an object with unknown class,
578 the *Completions* buffer will show the legal classes for each completion
579 like this:
580
581 MyMethod <Class1,Class2,Class3>
582
583 The value of this variable may be nil to inhibit display, or an integer to
584 indicate the maximum number of classes to display.
585
586 On XEmacs, a full list of classes will also be placed into a `help-echo'
587 property on the competion items, so that the list of classes for the current
588 item is displayed in the echo area.  If the value of this variable is a
589 negative integer, the `help-echo' property will be suppressed."
590   :group 'idlwave-completion
591   :type '(choice (const :tag "Don't show" nil)
592                  (integer :tag "Number of classes shown" 1)))
593
594 (defcustom idlwave-completion-fontify-classes t
595   "*Non-nil means, fontify the classes in completions buffer.
596 This makes it easier to distinguish the completion items from the extra
597 class info listed.  See `idlwave-completion-show-classes'."
598   :group 'idlwave-completion
599   :type 'boolean)
600
601 (defcustom idlwave-query-class '((method-default . nil)
602                                  (keyword-default . nil))
603   "Association list governing specification of object classes for completion.
604
605 When IDLWAVE tries to complete object-oriented methods, it usually
606 cannot determine the class of a given object from context.  In order
607 to provide the user with a correct list of methods or keywords, it
608 needs to determine the appropriate class.  IDLWAVE has two ways of
609 doing this (well, three ways if you count the shell... see
610 `idlwave-shell-query-for-class'):
611
612 1. Combine the items of all available classes which contain this
613    method for the purpose of completion.  So when completing a method,
614    all methods of all known classes are available, and when completing
615    a keyword, all keywords allowed for this method in any class are
616    shown.  This behavior is very much like normal completion and is
617    therefore the default.  It works much better than one might think -
618    only for the INIT, GETPROPERTY and SETPROPERTY the keyword lists
619    become uncomfortably long.  See also
620    `idlwave-completion-show-classes'.
621
622 2. The second possibility is to ask the user on each occasion.  To
623    make this less interruptive, IDLWAVE can store the class as a text
624    property on the object operator `->'.  For a given object in the
625    source code, class selection will then be needed only once
626    - for example to complete the method.  Keywords to the method can
627    then be completed directly, because the class is already known.
628    You will have to turn on the storage of the selected class
629    explicitly with the variable `idlwave-store-inquired-class'.
630
631 This variable allows you to configure IDLWAVE's method and
632 method-keyword completion behavior.  Its value is an alist, which
633 should contain at least two elements: (method-default . VALUE) and
634 \(keyword-default . VALUE), where VALUE is either t or nil.  These
635 specify if the class should be found during method and keyword
636 completion, respectively.
637
638 The alist may have additional entries specifying exceptions from the 
639 keyword completion rule for specific methods, like INIT or
640 GETPROPERTY.  In order to turn on class specification for the INIT
641 method, add an entry (\"INIT\" . t).  The method name must be ALL-CAPS."
642   :group 'idlwave-completion
643   :type '(list
644           (cons (const method-default)
645                 (boolean :tag "Determine class when completing METHODS    "))
646           (cons (const keyword-default)
647                 (boolean :tag "Determine class when completing KEYWORDS   "))
648           (repeat
649            :tag "Exceptions to defaults"
650            :inline t
651            (cons (string  :tag "MODULE" :value "")
652                  (boolean :tag "Determine class for this method")))))
653
654 (defcustom idlwave-store-inquired-class nil
655   "*Non-nil means, store class of a method call as text property on `->'.
656 IDLWAVE sometimes has to ask the user for the class associated with a
657 particular object method call.  This happens during the commands
658 `idlwave-routine-info' and `idlwave-complete', depending upon the
659 value of the variable `idlwave-query-class'.
660
661 When you specify a class, this information can be stored as a text
662 property on the `->' arrow in the source code, so that during the same 
663 editing session, IDLWAVE will not have to ask again.  When this
664 variable is non-nil, IDLWAVE will store and reuse the class information.
665 The class stored can be checked and removed with `\\[idlwave-routine-info]'
666 on the arrow.
667
668 The default of this variable is nil, since the result of commands then
669 is more predictable.  However, if you know what you are doing, it can
670 be nice to turn this on.
671
672 An arrow which knows the class will be highlighted with
673 `idlwave-class-arrow-face'.  The command \\[idlwave-routine-info]
674 displays (with prefix arg: deletes) the class stored on the arrow
675 at point."
676   :group 'idlwave-completion
677   :type 'boolean)
678
679 (defcustom idlwave-class-arrow-face 'bold
680   "*Face to highlight object operator arrows `->' which carry a class property.
681 When IDLWAVE stores a class name as text property on an object arrow
682 \(see variable `idlwave-store-inquired-class', it highlights the arrow
683 with this font in order to remind the user that this arrow is special."
684   :group 'idlwave-completion
685   :type 'symbol)
686
687 (defcustom idlwave-resize-routine-help-window t
688   "*Non-nil means, resize the Routine-info *Help* window to fit the content."
689   :group 'idlwave-completion
690   :type 'boolean)
691
692 (defcustom idlwave-keyword-completion-adds-equal t
693   "*Non-nil means, completion automatically adds `=' after completed keywords."
694   :group 'idlwave-completion
695   :type 'boolean)
696
697 (defcustom idlwave-function-completion-adds-paren t
698   "*Non-nil means, completion automatically adds `(' after completed function.
699 nil means, don't add anything.
700 A value of `2' means, also add the closing parenthesis and position cursor
701 between the two."
702   :group 'idlwave-completion
703   :type '(choice (const :tag "Nothing" nil)
704                  (const :tag "(" t)
705                  (const :tag "()" 2)))
706
707 (defcustom idlwave-completion-restore-window-configuration t
708   "*Non-nil means, try to restore the window configuration after completion.
709 When completion is not unique, Emacs displays a list of completions.
710 This messes up your window configuration.  With this variable set, IDLWAVE
711 restores the old configuration after successful completion."
712   :group 'idlwave-completion
713   :type 'boolean)
714
715 ;;; Variables for abbrev and action behavior -----------------------------
716
717 (defgroup idlwave-abbrev-and-indent-action nil
718   "IDLWAVE performs actions when expanding abbreviations or indenting lines.
719 The variables in this group govern this."
720   :group 'idlwave)
721
722 (defcustom idlwave-do-actions nil
723   "*Non-nil means performs actions when indenting.
724 The actions that can be performed are listed in `idlwave-indent-action-table'."
725   :group 'idlwave-abbrev-and-indent-action
726   :type 'boolean)
727
728 (defcustom idlwave-abbrev-start-char "\\"
729   "*A single character string used to start abbreviations in abbrev mode.
730 Possible characters to chose from: ~`\%
731 or even '?'.  '.' is not a good choice because it can make structure
732 field names act like abbrevs in certain circumstances.
733
734 Changes to this in `idlwave-mode-hook' will have no effect.  Instead a user
735 must set it directly using `setq' in the .emacs file before idlwave.el
736 is loaded."
737   :group 'idlwave-abbrev-and-indent-action
738   :type 'string)
739
740 (defcustom idlwave-surround-by-blank nil
741   "*Non-nil means, enable `idlwave-surround'.
742 If non-nil, `=',`<',`>',`&',`,', `->' are surrounded with spaces by
743 `idlwave-surround'.
744 See help for `idlwave-indent-action-table' for symbols using `idlwave-surround'.
745
746 Also see the default key bindings for keys using `idlwave-surround'.
747 Keys are bound and made into actions calling `idlwave-surround' with
748 `idlwave-action-and-binding'.
749 See help for `idlwave-action-and-binding' for examples.
750
751 Also see help for `idlwave-surround'."
752   :group 'idlwave-abbrev-and-indent-action
753   :type 'boolean)
754
755 (defcustom idlwave-pad-keyword t
756   "*Non-nil means pad '=' for keywords like assignments.
757 Whenever `idlwave-surround' is non-nil then this affects how '=' is padded
758 for keywords.  If t, it is padded the same as for assignments.
759 If nil then spaces are removed.  With any other value, spaces are left
760 unchanged."
761   :group 'idlwave-abbrev-and-indent-action
762   :type '(choice
763           (const :tag "Pad like assignments" t)
764           (const :tag "Remove space near `='" nil)
765           (const :tag "Keep space near `='" 'keep)))
766
767 (defcustom idlwave-show-block t
768   "*Non-nil means point blinks to block beginning for `idlwave-show-begin'."
769   :group 'idlwave-abbrev-and-indent-action
770   :type 'boolean)
771
772 (defcustom idlwave-expand-generic-end nil
773   "*Non-nil means expand generic END to ENDIF/ENDELSE/ENDWHILE etc."
774   :group 'idlwave-abbrev-and-indent-action
775   :type 'boolean)
776
777 (defcustom idlwave-reindent-end t
778   "*Non-nil means re-indent line after END was typed."
779   :group 'idlwave-abbrev-and-indent-action
780   :type 'boolean)
781
782 (defcustom idlwave-abbrev-move t
783   "*Non-nil means the abbrev hook can move point.
784 Set to nil by `idlwave-expand-region-abbrevs'. To see the abbrev
785 definitions, use the command `list-abbrevs', for abbrevs that move
786 point. Moving point is useful, for example, to place point between
787 parentheses of expanded functions.
788
789 See `idlwave-check-abbrev'."
790   :group 'idlwave-abbrev-and-indent-action
791   :type 'boolean)
792
793 (defcustom idlwave-abbrev-change-case nil
794   "*Non-nil means all abbrevs will be forced to either upper or lower case.
795 If the value t, all expanded abbrevs will be upper case.
796 If the value is 'down then abbrevs will be forced to lower case.
797 If nil, the case will not change.
798 If `idlwave-reserved-word-upcase' is non-nil, reserved words will always be
799 upper case, regardless of this variable."
800   :group 'idlwave-abbrev-and-indent-action
801   :type 'boolean)
802
803 (defcustom idlwave-reserved-word-upcase nil
804   "*Non-nil means, reserved words will be made upper case via abbrev expansion.
805 If nil case of reserved words is controlled by `idlwave-abbrev-change-case'.
806 Has effect only if in abbrev-mode."
807   :group 'idlwave-abbrev-and-indent-action
808   :type 'boolean)
809
810 ;;; Action/Expand Tables.
811 ;;
812 ;; The average user may have difficulty modifying this directly.  It
813 ;; can be modified/set in idlwave-mode-hook, but it is easier to use
814 ;; idlwave-action-and-binding. See help for idlwave-action-and-binding for
815 ;; examples of how to add an action.
816 ;;
817 ;; The action table is used by `idlwave-indent-line' whereas both the
818 ;; action and expand tables are used by `idlwave-indent-and-action'.  In
819 ;; general, the expand table is only used when a line is explicitly
820 ;; indented.  Whereas, in addition to being used when the expand table
821 ;; is used, the action table is used when a line is indirectly
822 ;; indented via line splitting, auto-filling or a new line creation.
823 ;;
824 ;; Example actions:
825 ;;
826 ;;  Capitalize system vars
827 ;;   (idlwave-action-and-binding idlwave-sysvar '(capitalize-word 1) t)
828 ;;
829 ;;  Capitalize procedure name
830 ;;   (idlwave-action-and-binding "\\<\\(pro\\|function\\)\\>[ \t]*\\<"
831 ;;                           '(capitalize-word 1) t)
832 ;;
833 ;;  Capitalize common block name
834 ;;   (idlwave-action-and-binding "\\<common\\>[ \t]+\\<"
835 ;;                           '(capitalize-word 1) t)
836 ;;  Capitalize label
837 ;;   (idlwave-action-and-binding (concat "^[ \t]*" idlwave-label)
838 ;;                           '(capitalize-word -1) t)
839
840 (defvar idlwave-indent-action-table nil
841   "*Associated array containing action lists of search string (car),
842 and function as a cdr. This table is used by `idlwave-indent-line'.
843 See documentation for `idlwave-do-action' for a complete description of
844 the action lists.
845
846 Additions to the table are made with `idlwave-action-and-binding' when a
847 binding is not requested.
848 See help on `idlwave-action-and-binding' for examples.")
849
850 (defvar idlwave-indent-expand-table nil
851   "*Associated array containing action lists of search string (car),
852 and function as a cdr. The table is used by the
853 `idlwave-indent-and-action' function. See documentation for
854 `idlwave-do-action' for a complete description of the action lists.
855
856 Additions to the table are made with `idlwave-action-and-binding' when a
857 binding is requested.
858 See help on `idlwave-action-and-binding' for examples.")
859
860 ;;; Documentation header and history keyword ---------------------------------
861
862 (defgroup idlwave-documentation nil
863   "Options for documenting IDLWAVE files."
864   :group 'idlwave)
865
866 ;; FIXME: make defcustom?
867 (defvar idlwave-file-header
868   (list nil
869         ";+
870 ; NAME:
871 ;
872 ;
873 ;
874 ; PURPOSE:
875 ;
876 ;
877 ;
878 ; CATEGORY:
879 ;
880 ;
881 ;
882 ; CALLING SEQUENCE:
883 ;
884 ;
885 ;
886 ; INPUTS:
887 ;
888 ;
889 ;
890 ; OPTIONAL INPUTS:
891 ;
892 ;
893 ;
894 ; KEYWORD PARAMETERS:
895 ;
896 ;
897 ;
898 ; OUTPUTS:
899 ;
900 ;
901 ;
902 ; OPTIONAL OUTPUTS:
903 ;
904 ;
905 ;
906 ; COMMON BLOCKS:
907 ;
908 ;
909 ;
910 ; SIDE EFFECTS:
911 ;
912 ;
913 ;
914 ; RESTRICTIONS:
915 ;
916 ;
917 ;
918 ; PROCEDURE:
919 ;
920 ;
921 ;
922 ; EXAMPLE:
923 ;
924 ;
925 ;
926 ; MODIFICATION HISTORY:
927 ;
928 ;-
929 ")
930   "*A list (PATHNAME STRING) specifying the doc-header template to use for
931 summarizing a file. If PATHNAME is non-nil then this file will be included.
932 Otherwise STRING is used. If nil, the file summary will be omitted.
933 For example you might set PATHNAME to the path for the
934 lib_template.pro file included in the IDL distribution.")
935
936 (defcustom idlwave-header-to-beginning-of-file nil
937   "*Non-nil means, the documentation header will always be at start of file.
938 When nil, the header is positioned between the PRO/FUNCTION line of
939 the current routine and the code, allowing several routine headers in
940 a file."
941   :group 'idlwave-documentation
942   :type 'boolean)
943
944 (defcustom idlwave-timestamp-hook 'idlwave-default-insert-timestamp
945   "*The hook function used to update the timestamp of a function."
946   :group 'idlwave-documentation
947   :type 'function)
948
949 (defcustom idlwave-doc-modifications-keyword "HISTORY"
950   "*The modifications keyword to use with the log documentation commands.
951 A ':' is added to the keyword end.
952 Inserted by doc-header and used to position logs by doc-modification.
953 If nil it will not be inserted."
954   :group 'idlwave-documentation
955   :type 'string)
956
957 (defcustom idlwave-doclib-start "^;+\\+"
958   "*Regexp matching the start of a document library header."
959   :group 'idlwave-documentation
960   :type 'regexp)
961
962 (defcustom idlwave-doclib-end "^;+-"
963   "*Regexp matching the end of a document library header."
964   :group 'idlwave-documentation
965   :type 'regexp)
966
967 ;;; External Programs -------------------------------------------------------
968
969 (defgroup idlwave-external-programs nil
970   "Path locations of external commands used by IDLWAVE."
971   :group 'idlwave)
972
973 ;; WARNING: The following variable has recently been moved from
974 ;; idlw-shell.el to this file.  I hope this does not break
975 ;; anything.
976
977 (defcustom idlwave-shell-explicit-file-name "idl"
978   "*If non-nil, this is the command to run IDL.
979 Should be an absolute file path or path relative to the current environment
980 execution search path.  If you want to specify command line switches
981 for the idl program, use `idlwave-shell-command-line-options'.
982
983 I know the name of this variable is badly chosen, but I cannot change
984 it without compromizing backwards-compatibility."
985   :group 'idlwave-external-programs
986   :type 'string)
987
988 (defcustom idlwave-shell-command-line-options nil
989   "*A list of command line options for calling the IDL program.
990 Since IDL is executed directly without going through a shell like /bin/sh,
991 this should be a list of strings like '(\"-rt=file\" \"-nw\") with a separate
992 string for each argument.  But you may also give a single string which
993 contains the options whitespace-separated.  Emacs will be kind enough to
994 split it for you."
995   :type '(choice
996           string
997           (repeat (string :value "")))
998   :group 'idlwave-external-programs)
999
1000 (defcustom idlwave-help-application "idlhelp"
1001   "*The external application providing reference help for programming."
1002   :group 'idlwave-external-programs
1003   :type 'string)
1004
1005 ;;; Some Shell variables which must be defined here.-----------------------
1006
1007 (defcustom idlwave-shell-debug-modifiers '()
1008   "List of modifiers to be used for the debugging commands.
1009 Will be used to bind debugging commands in the shell buffer and in all
1010 source buffers.  These are additional convenience bindings, the debugging
1011 commands are always available with the `C-c C-d' prefix.
1012 If you set this to '(control shift), this means setting a breakpoint will
1013 be on `C-S-b', compiling a source file on `C-S-c' etc.  Possible modifiers
1014 are `control', `meta', `super', `hyper', `alt', and `shift'."
1015   :group 'idlwave-shell-general-setup
1016   :type '(set :tag "Specify modifiers"
1017                (const control)
1018                (const meta)
1019                (const super)
1020                (const hyper)
1021                (const alt)
1022                (const shift)))
1023
1024 (defcustom idlwave-shell-automatic-start nil
1025   "*If non-nil attempt invoke idlwave-shell if not already running.
1026 This is checked when an attempt to send a command to an
1027 IDL process is made."
1028   :group 'idlwave-shell-general-setup
1029   :type 'boolean)
1030
1031 ;;; Miscellaneous variables -------------------------------------------------
1032
1033 (defgroup idlwave-misc nil
1034   "Miscellaneous options for IDLWAVE mode."
1035   :group 'idlwave)
1036
1037 (defcustom idlwave-startup-message t
1038   "*Non-nil displays a startup message when `idlwave-mode' is first called."
1039   :group 'idlwave-misc
1040   :type 'boolean)
1041
1042 (defcustom idlwave-default-font-lock-items 
1043   '(pros-and-functions batch-files idlwave-idl-keywords label goto
1044                        common-blocks class-arrows)
1045   "Items which should be fontified on the default fontification level 2.
1046 IDLWAVE defines 3 levels of fontification.  Level 1 is very little, level 3
1047 is everything and level 2 is specified by this list.
1048 This variable must be set before IDLWAVE gets loaded.  It is
1049 a list of symbols, the following symbols are allowed.
1050
1051 pros-and-functions   Procedure and Function definitions
1052 batch-files          Batch Files
1053 idlwave-idl-keywords IDL Keywords
1054 label                Statement Labels
1055 goto                 Goto Statements
1056 common-blocks        Common Blocks
1057 keyword-parameters   Keyword Parameters in routine definitions and calls
1058 system-variables     System Variables
1059 fixme                FIXME: Warning in comments (on XEmacs only v. 21.0 and up)
1060 class-arrows         Object Arrows with class property"
1061   :group 'idlwave-misc
1062   :type '(set
1063           :inline t :greedy t
1064           (const :tag "Procedure and Function definitions" pros-and-functions)
1065           (const :tag "Batch Files"                       batch-files)
1066           (const :tag "IDL Keywords (reserved words)"     idlwave-idl-keywords)
1067           (const :tag "Statement Labels"                  label)
1068           (const :tag "Goto Statements"                   goto)
1069           (const :tag "Tags in Structure Definition"      structtag)
1070           (const :tag "Structure Name"                    structname)
1071           (const :tag "Common Blocks"                     common-blocks)
1072           (const :tag "Keyword Parameters"                keyword-parameters)
1073           (const :tag "System Variables"                  system-variables)
1074           (const :tag "FIXME: Warning"                    fixme)
1075           (const :tag "Object Arrows with class property " class-arrows)))
1076
1077 (defcustom idlwave-mode-hook nil
1078   "Normal hook.  Executed when a buffer is put into `idlwave-mode'."
1079   :group 'idlwave-misc
1080   :type 'hook)
1081
1082 (defcustom idlwave-load-hook nil
1083   "Normal hook.  Executed when idlwave.el is loaded."
1084   :group 'idlwave-misc
1085   :type 'hook)
1086
1087 (defvar idlwave-experimental nil
1088   "Non-nil means turn on a few experimental features.
1089 This variable is only for the maintainer, to test difficult stuff,
1090 while still distributing stable releases.
1091 As a user, you should not set this to t.")
1092
1093 ;;;
1094 ;;; End customization variables section
1095 ;;;
1096
1097 ;;; Non customization variables
1098
1099 ;;; font-lock mode - Additions by Phil Williams, Ulrik Dickow and
1100 ;;; Simon Marshall <simon@gnu.ai.mit.edu>
1101 ;;; and Carsten Dominik...
1102
1103 ;; The following are the reserved words in IDL.  Maybe we should
1104 ;; highlight some more stuff as well?       
1105 ;; Procedure declarations.  Fontify keyword plus procedure name.
1106 (defvar idlwave-idl-keywords
1107   ;; To update this regexp, update the list of keywords and 
1108   ;; evaluate the form.
1109   ;;    (insert 
1110   ;;     (prin1-to-string
1111   ;;      (concat 
1112   ;;       "\\<\\("
1113   ;;       (regexp-opt 
1114   ;;        '("and" "or" "xor" "not"
1115   ;;          "eq" "ge" "gt" "le" "lt" "ne" 
1116   ;;          "for" "do" "endfor"
1117   ;;          "if" "then" "endif" "else" "endelse" 
1118   ;;          "case" "of" "endcase"
1119   ;;          "switch" "break" "continue" "endswitch"
1120   ;;          "begin" "end"
1121   ;;          "repeat" "until" "endrep"
1122   ;;          "while" "endwhile" 
1123   ;;          "goto" "return"
1124   ;;          "inherits" "mod"
1125   ;;          "compile_opt" "forward_function"
1126   ;;          "on_error" "on_ioerror"))  ; on_error is not officially reserved
1127   ;;       "\\)\\>")))
1128   "\\<\\(and\\|b\\(egin\\|reak\\)\\|c\\(ase\\|o\\(mpile_opt\\|ntinue\\)\\)\\|do\\|e\\(lse\\|nd\\(case\\|else\\|for\\|if\\|rep\\|switch\\|while\\)?\\|q\\)\\|for\\(ward_function\\)?\\|g\\(oto\\|[et]\\)\\|i\\(f\\|nherits\\)\\|l[et]\\|mod\\|n\\(e\\|ot\\)\\|o\\(n_\\(error\\|ioerror\\)\\|[fr]\\)\\|re\\(peat\\|turn\\)\\|switch\\|then\\|until\\|while\\|xor\\)\\>")
1129
1130 (let* (;; Procedure declarations.  Fontify keyword plus procedure name.
1131        ;; Function  declarations.  Fontify keyword plus function  name.
1132        (pros-and-functions
1133         '("\\<\\(function\\|pro\\)\\>[ \t]+\\(\\sw+\\(::\\sw+\\)?\\)"
1134           (1 font-lock-keyword-face)
1135           (2 font-lock-function-name-face nil t)))
1136
1137        ;; Common blocks
1138        (common-blocks
1139         '("\\<\\(common\\)\\>[ \t]*\\(\\sw+\\)?[ \t]*,?"
1140           (1 font-lock-keyword-face)              ; "common"
1141           (2 font-lock-reference-face nil t)      ; block name
1142           (font-lock-match-c++-style-declaration-item-and-skip-to-next
1143            ;; Start with point after block name and comma
1144            (goto-char (match-end 0))  ; needed for XEmacs, could be nil 
1145            nil
1146            (1 font-lock-variable-name-face)       ; variable names
1147            )))
1148
1149        ;; Batch files
1150        (batch-files
1151         '("^[ \t]*\\(@[^ \t\n]+\\)" (1 font-lock-string-face)))
1152
1153        ;; FIXME warning.
1154        (fixme
1155         '("\\<FIXME:" (0 font-lock-warning-face t)))
1156
1157        ;; Labels
1158        (label
1159         '("^[ \t]*\\([a-zA-Z]\\sw*:\\)" (1 font-lock-reference-face)))
1160
1161        ;; The goto statement and its label
1162        (goto
1163         '("\\(goto\\)[ \t]*,[ \t]*\\([a-zA-Z]\\sw*\\)"
1164           (1 font-lock-keyword-face)
1165           (2 font-lock-reference-face)))
1166
1167        ;; Tags in structure definitions.  Note that this definition
1168        ;; actually collides with labels, so we have to use the same
1169        ;; face.  It also matches named subscript ranges,
1170        ;; e.g. vec{bottom:top].  No good way around this.
1171        (structtag
1172         '("\\<\\([a-zA-Z][a-zA-Z0-9_]*:\\)[^:]" (1 font-lock-reference-face)))
1173
1174        ;; Structure names
1175        (structname
1176         '("\\({\\|\\<inherits\\s-\\)\\s-*\\([a-zA-Z][a-zA-Z0-9_]*\\)[},\t \n]"
1177           (2 font-lock-function-name-face)))
1178
1179        ;; Keyword parameters, like /xlog or ,xrange=[]
1180        ;; This is anchored to the comma preceeding the keyword.
1181        ;; Treats continuation lines, works only during whole buffer
1182        ;; fontification.  Slow, use it only in fancy fontification.
1183        (keyword-parameters
1184         '("\\(,\\|[a-zA-Z0-9_](\\)[ \t]*\\(\\$[ \t]*\\(;.*\\)?\\(\n[ \t]*;.*\\)*\n[ \t]*\\)?\\(/[a-zA-Z_]\\sw*\\|[a-zA-Z_]\\sw*[ \t]*=\\)"
1185           (5 font-lock-reference-face)))
1186
1187        ;; System variables start with a bang.
1188        (system-variables
1189         '("\\(![a-zA-Z_0-9]+\\(\\.\\sw+\\)?\\)"
1190           (1 font-lock-variable-name-face)))
1191
1192        ;; Special and unusual operators (not used because too noisy)
1193        (special-operators
1194         '("[<>#]" (0 font-lock-keyword-face)))
1195
1196        ;; All operators (not used because too noisy)
1197        (all-operators
1198         '("[-*^#+<>/]" (0 font-lock-keyword-face)))
1199         
1200        ;; Arrows with text property `idlwave-class'
1201        (class-arrows
1202         '(idlwave-match-class-arrows (0 idlwave-class-arrow-face))))
1203
1204   (defconst idlwave-font-lock-keywords-1
1205     (list pros-and-functions batch-files)
1206     "Subdued level highlighting for IDLWAVE mode.")
1207
1208   (defconst idlwave-font-lock-keywords-2
1209     (mapcar 'symbol-value idlwave-default-font-lock-items)
1210     "Medium level highlighting for IDLWAVE mode.")
1211
1212   (defconst idlwave-font-lock-keywords-3
1213         (list pros-and-functions
1214               batch-files
1215               idlwave-idl-keywords
1216               label goto
1217               structtag
1218               structname
1219               common-blocks
1220               keyword-parameters
1221               system-variables
1222           class-arrows)
1223     "Gaudy level highlighting for IDLWAVE mode."))
1224
1225 (defun idlwave-match-class-arrows (limit)
1226   ;; Match an object arrow with class property
1227   (and idlwave-store-inquired-class
1228        (re-search-forward "->" limit 'limit)
1229        (get-text-property (match-beginning 0) 'idlwave-class)))
1230
1231 (defvar idlwave-font-lock-keywords idlwave-font-lock-keywords-2
1232   "Default expressions to highlight in IDLWAVE mode.")
1233
1234 (defvar idlwave-font-lock-defaults
1235   '((idlwave-font-lock-keywords
1236      idlwave-font-lock-keywords-1 
1237      idlwave-font-lock-keywords-2
1238      idlwave-font-lock-keywords-3)
1239     nil t 
1240     ((?$ . "w") (?_ . "w") (?. . "w")) 
1241     beginning-of-line))
1242
1243 (put 'idlwave-mode 'font-lock-defaults 
1244      idlwave-font-lock-defaults) ; XEmacs
1245
1246 (defconst idlwave-comment-line-start-skip "^[ \t]*;"
1247   "Regexp to match the start of a full-line comment.
1248 That is the _beginning_ of a line containing a comment delimiter `;' preceded
1249 only by whitespace.")
1250
1251 (defconst idlwave-begin-block-reg 
1252   "\\<\\(pro\\|function\\|begin\\|case\\|switch\\)\\>"
1253   "Regular expression to find the beginning of a block. The case does
1254 not matter. The search skips matches in comments.")
1255
1256 (defconst idlwave-begin-unit-reg "^\\s-*\\(pro\\|function\\)\\>\\|\\`"
1257   "Regular expression to find the beginning of a unit. The case does
1258 not matter.")
1259
1260 (defconst idlwave-end-unit-reg "^\\s-*\\(pro\\|function\\)\\>\\|\\'"
1261   "Regular expression to find the line that indicates the end of unit.
1262 This line is the end of buffer or the start of another unit. The case does
1263 not matter. The search skips matches in comments.")
1264
1265 (defconst idlwave-continue-line-reg "\\<\\$"
1266   "Regular expression to match a continued line.")
1267
1268 (defconst idlwave-end-block-reg
1269   "\\<end\\(\\|case\\|switch\\|else\\|for\\|if\\|rep\\|while\\)\\>"
1270   "Regular expression to find the end of a block. The case does
1271 not matter. The search skips matches found in comments.")
1272
1273 (defconst idlwave-block-matches
1274   '(("pro"      . "end")
1275     ("function" . "end")
1276     ("case"     . "endcase")
1277     ("else"     . "endelse")
1278     ("for"      . "endfor")
1279     ("then"     . "endif")
1280     ("repeat"   . "endrep")
1281     ("switch"   . "endswitch")
1282     ("while"    . "endwhile"))
1283   "Matches between statements and the corresponding END variant.
1284 The cars are the reserved words starting a block.  If the block really
1285 begins with BEGIN, the cars are the reserved words before the begin
1286 which can be used to identify the block type.
1287 This is used to check for the correct END type, to close blocks and
1288 to expand generic end statements to their detailed form.")
1289
1290 (defconst idlwave-block-match-regexp
1291   "\\<\\(else\\|for\\|then\\|repeat\\|while\\)\\>"
1292 "Regular expression matching reserved words which can stand before
1293 blocks starting with a BEGIN statement.  The matches must have associations
1294 `idlwave-block-matches'")
1295
1296 (defconst idlwave-identifier "[a-zA-Z][a-zA-Z0-9$_]*"
1297   "Regular expression matching an IDL identifier.")
1298
1299 (defconst idlwave-sysvar (concat "!" idlwave-identifier)
1300   "Regular expression matching IDL system variables.")
1301
1302 (defconst idlwave-variable (concat idlwave-identifier "\\|" idlwave-sysvar)
1303   "Regular expression matching IDL variable names.")
1304
1305 (defconst idlwave-label (concat idlwave-identifier ":")
1306   "Regular expression matching IDL labels.")
1307
1308 (defconst idlwave-method-call (concat idlwave-identifier  "\\s *->"
1309                                       "\\(\\s *" idlwave-identifier "::\\)?"
1310 ))
1311
1312 (defconst idlwave-statement-match
1313   (list
1314    ;; "endif else" is the only possible "end" that can be
1315    ;; followed by a statement on the same line.
1316    '(endelse . ("end\\(\\|if\\)\\s +else" "end\\(\\|if\\)\\s +else"))
1317    ;; all other "end"s can not be followed by a statement.
1318    (cons 'end (list idlwave-end-block-reg nil))
1319    '(if . ("if\\>" "then"))
1320    '(for . ("for\\>" "do"))
1321    '(begin . ("begin\\>" nil))
1322    '(pdef . ("pro\\>\\|function\\>" nil))
1323    '(while . ("while\\>" "do"))
1324    '(repeat . ("repeat\\>" "repeat"))
1325    '(goto . ("goto\\>" nil))
1326    '(case . ("case\\>" nil))
1327    '(switch . ("switch\\>" nil))
1328    (cons 'call (list (concat "\\(" idlwave-variable "\\) *= *" 
1329                              "\\(" idlwave-method-call "\\s *\\)?"
1330                              idlwave-identifier
1331                              "\\s *(") nil))
1332    (cons 'call (list (concat 
1333                       "\\(" idlwave-method-call "\\s *\\)?"
1334                       idlwave-identifier 
1335                       "\\( *$\\|\\s *,\\)") nil))
1336    (cons 'assign (list (concat 
1337                         "\\(" idlwave-variable "\\) *=") nil)))
1338   
1339   "Associated list of statement matching regular expressions.
1340 Each regular expression matches the start of an IDL statement.  The
1341 first element of each association is a symbol giving the statement
1342 type.  The associated value is a list.  The first element of this list
1343 is a regular expression matching the start of an IDL statement for
1344 identifying the statement type.  The second element of this list is a
1345 regular expression for finding a substatement for the type.  The
1346 substatement starts after the end of the found match modulo
1347 whitespace.  If it is nil then the statement has no substatement.  The
1348 list order matters since matching an assignment statement exactly is
1349 not possible without parsing.  Thus assignment statement become just
1350 the leftover unidentified statements containing an equal sign."  )
1351
1352 (defvar idlwave-fill-function 'auto-fill-function
1353   "IDL mode auto fill function.")
1354
1355 (defvar idlwave-comment-indent-function 'comment-indent-function
1356   "IDL mode comment indent function.")
1357
1358 ;; Note that this is documented in the v18 manuals as being a string
1359 ;; of length one rather than a single character.
1360 ;; The code in this file accepts either format for compatibility.
1361 (defvar idlwave-comment-indent-char ?\ 
1362   "Character to be inserted for IDL comment indentation.
1363 Normally a space.")
1364
1365 (defconst idlwave-continuation-char ?$
1366   "Character which is inserted as a last character on previous line by
1367    \\[idlwave-split-line] to begin a continuation line.  Normally $.")
1368
1369 (defconst idlwave-mode-version "5.1")
1370
1371 (defmacro idlwave-keyword-abbrev (&rest args)
1372   "Creates a function for abbrev hooks to call `idlwave-check-abbrev' with args."
1373   `(quote (lambda ()
1374             ,(append '(idlwave-check-abbrev) args))))
1375
1376 ;; If I take the time I can replace idlwave-keyword-abbrev with
1377 ;; idlwave-code-abbrev and remove the quoted abbrev check from
1378 ;; idlwave-check-abbrev.  Then, e.g, (idlwave-keyword-abbrev 0 t) becomes
1379 ;; (idlwave-code-abbrev idlwave-check-abbrev 0 t).  In fact I should change
1380 ;; the name of idlwave-check-abbrev to something like idlwave-modify-abbrev.
1381
1382 (defmacro idlwave-code-abbrev (&rest args)
1383   "Creates a function for abbrev hooks that ensures abbrevs are not quoted.
1384 Specifically, if the abbrev is in a comment or string it is unexpanded.
1385 Otherwise ARGS forms a list that is evaluated."
1386   `(quote (lambda ()
1387             ,(prin1-to-string args)  ;; Puts the code in the doc string
1388             (if (idlwave-quoted)
1389                 (progn (unexpand-abbrev) nil)
1390               ,(append args)))))
1391
1392 (defvar idlwave-mode-map (make-sparse-keymap)
1393   "Keymap used in IDL mode.")
1394
1395 (defvar idlwave-mode-syntax-table (make-syntax-table)
1396   "Syntax table in use in `idlwave-mode' buffers.")
1397
1398 (modify-syntax-entry ?+   "."  idlwave-mode-syntax-table)
1399 (modify-syntax-entry ?-   "."  idlwave-mode-syntax-table)
1400 (modify-syntax-entry ?*   "."  idlwave-mode-syntax-table)
1401 (modify-syntax-entry ?/   "."  idlwave-mode-syntax-table)
1402 (modify-syntax-entry ?^   "."  idlwave-mode-syntax-table)
1403 (modify-syntax-entry ?#   "."  idlwave-mode-syntax-table)
1404 (modify-syntax-entry ?=   "."  idlwave-mode-syntax-table)
1405 (modify-syntax-entry ?%   "."  idlwave-mode-syntax-table)
1406 (modify-syntax-entry ?<   "."  idlwave-mode-syntax-table)
1407 (modify-syntax-entry ?>   "."  idlwave-mode-syntax-table)
1408 (modify-syntax-entry ?\'  "\"" idlwave-mode-syntax-table)
1409 (modify-syntax-entry ?\"  "\"" idlwave-mode-syntax-table)
1410 (modify-syntax-entry ?\\  "."  idlwave-mode-syntax-table)
1411 (modify-syntax-entry ?_   "_"  idlwave-mode-syntax-table)
1412 (modify-syntax-entry ?{   "(}" idlwave-mode-syntax-table)
1413 (modify-syntax-entry ?}   "){" idlwave-mode-syntax-table)
1414 (modify-syntax-entry ?$   "_"  idlwave-mode-syntax-table)
1415 (modify-syntax-entry ?.   "."  idlwave-mode-syntax-table)
1416 (modify-syntax-entry ?\;  "<"  idlwave-mode-syntax-table)
1417 (modify-syntax-entry ?\n  ">"  idlwave-mode-syntax-table)
1418 (modify-syntax-entry ?\f  ">"  idlwave-mode-syntax-table)
1419
1420 (defvar idlwave-find-symbol-syntax-table
1421   (copy-syntax-table idlwave-mode-syntax-table)
1422   "Syntax table that treats symbol characters as word characters.")
1423
1424 (modify-syntax-entry ?$   "w"  idlwave-find-symbol-syntax-table)
1425 (modify-syntax-entry ?_   "w"  idlwave-find-symbol-syntax-table)
1426 (modify-syntax-entry ?!   "w"  idlwave-find-symbol-syntax-table)
1427 (modify-syntax-entry ?.   "w"  idlwave-find-symbol-syntax-table)
1428
1429 (defmacro idlwave-with-special-syntax (&rest body)
1430   "Execute BODY with a different syntax table."
1431   `(let ((saved-syntax (syntax-table)))
1432      (unwind-protect
1433          (progn
1434            (set-syntax-table idlwave-find-symbol-syntax-table)
1435            ,@body)
1436        (set-syntax-table saved-syntax))))
1437
1438 ;(defmacro idlwave-with-special-syntax1 (&rest body)
1439 ;  "Execute BODY with a different syntax table."
1440 ;  `(let ((saved-syntax (syntax-table)))
1441 ;     (unwind-protect
1442 ;         (progn
1443 ;           (set-syntax-table idlwave-find-symbol-syntax-table)
1444 ;           ,@body)
1445 ;       (set-syntax-table saved-syntax))))
1446
1447 (defun idlwave-action-and-binding (key cmd &optional select)
1448   "KEY and CMD are made into a key binding and an indent action.
1449 KEY is a string - same as for the `define-key' function.  CMD is a
1450 function of no arguments or a list to be evaluated.  CMD is bound to
1451 KEY in `idlwave-mode-map' by defining an anonymous function calling
1452 `self-insert-command' followed by CMD.  If KEY contains more than one
1453 character a binding will only be set if SELECT is 'both.
1454
1455 \(KEY . CMD\) is also placed in the `idlwave-indent-expand-table',
1456 replacing any previous value for KEY.  If a binding is not set then it
1457 will instead be placed in `idlwave-indent-action-table'.
1458
1459 If the optional argument SELECT is nil then an action and binding are
1460 created.  If SELECT is 'noaction, then a binding is always set and no
1461 action is created.  If SELECT is 'both then an action and binding
1462 will both be created even if KEY contains more than one character.
1463 Otherwise, if SELECT is non-nil then only an action is created.
1464
1465 Some examples:
1466 No spaces before and 1 after a comma
1467    (idlwave-action-and-binding \",\"  '(idlwave-surround 0 1))
1468 A minimum of 1 space before and after `=' (see `idlwave-expand-equal').
1469    (idlwave-action-and-binding \"=\"  '(idlwave-expand-equal -1 -1))
1470 Capitalize system variables - action only
1471    (idlwave-action-and-binding idlwave-sysvar '(capitalize-word 1) t)"
1472   (if (not (equal select 'noaction))
1473       ;; Add action
1474       (let* ((table (if select 'idlwave-indent-action-table
1475                       'idlwave-indent-expand-table))
1476              (cell (assoc key (eval table))))
1477         (if cell
1478             ;; Replace action command
1479             (setcdr cell cmd)
1480           ;; New action
1481           (set table (append (eval table) (list (cons key cmd)))))))
1482   ;; Make key binding for action
1483   (if (or (and (null select) (= (length key) 1))
1484           (equal select 'noaction)
1485           (equal select 'both))
1486       (define-key idlwave-mode-map key
1487         (append '(lambda ()
1488                             (interactive)
1489                             (self-insert-command 1))
1490                 (list (if (listp cmd)
1491                           cmd
1492                         (list cmd)))))))
1493
1494 (fset 'idlwave-debug-map (make-sparse-keymap))
1495
1496 (define-key idlwave-mode-map "\C-c "    'idlwave-hard-tab)
1497 (define-key idlwave-mode-map [(control tab)] 'idlwave-hard-tab)
1498 ;(define-key idlwave-mode-map "\C-c\C- " 'idlwave-hard-tab)
1499 (define-key idlwave-mode-map "'"        'idlwave-show-matching-quote)
1500 (define-key idlwave-mode-map "\""       'idlwave-show-matching-quote)
1501 (define-key idlwave-mode-map "\C-g"     'idlwave-keyboard-quit)
1502 (define-key idlwave-mode-map "\C-c;"    'idlwave-toggle-comment-region)
1503 (define-key idlwave-mode-map "\C-\M-a"  'idlwave-beginning-of-subprogram)
1504 (define-key idlwave-mode-map "\C-\M-e"  'idlwave-end-of-subprogram)
1505 (define-key idlwave-mode-map "\C-c{"    'idlwave-beginning-of-block)
1506 (define-key idlwave-mode-map "\C-c}"    'idlwave-end-of-block)
1507 (define-key idlwave-mode-map "\C-c]"    'idlwave-close-block)
1508 (define-key idlwave-mode-map "\M-\C-h"  'idlwave-mark-subprogram)
1509 (define-key idlwave-mode-map "\M-\C-n"  'idlwave-forward-block)
1510 (define-key idlwave-mode-map "\M-\C-p"  'idlwave-backward-block)
1511 (define-key idlwave-mode-map "\M-\C-d"  'idlwave-down-block)
1512 (define-key idlwave-mode-map "\M-\C-u"  'idlwave-backward-up-block)
1513 (define-key idlwave-mode-map "\M-\r"    'idlwave-split-line)
1514 (define-key idlwave-mode-map "\M-\C-q"  'idlwave-indent-subprogram)
1515 (define-key idlwave-mode-map "\C-c\C-p" 'idlwave-previous-statement)
1516 (define-key idlwave-mode-map "\C-c\C-n" 'idlwave-next-statement)
1517 ;; (define-key idlwave-mode-map "\r"       'idlwave-newline)
1518 ;; (define-key idlwave-mode-map "\t"       'idlwave-indent-line)
1519 (define-key idlwave-mode-map [(shift tab)] 'idlwave-indent-statement)
1520 (define-key idlwave-mode-map "\C-c\C-a" 'idlwave-auto-fill-mode)
1521 (define-key idlwave-mode-map "\M-q"     'idlwave-fill-paragraph)
1522 (define-key idlwave-mode-map "\M-s"     'idlwave-edit-in-idlde)
1523 (define-key idlwave-mode-map "\C-c\C-h" 'idlwave-doc-header)
1524 (define-key idlwave-mode-map "\C-c\C-m" 'idlwave-doc-modification)
1525 (define-key idlwave-mode-map "\C-c\C-c" 'idlwave-case)
1526 (define-key idlwave-mode-map "\C-c\C-d" 'idlwave-debug-map)
1527 (when (and (boundp 'idlwave-shell-debug-modifiers)
1528          (listp idlwave-shell-debug-modifiers)
1529          (not (equal idlwave-shell-debug-modifiers '())))
1530   ;; Bind the debug commands also with the special modifiers.
1531   (let ((shift (memq 'shift idlwave-shell-debug-modifiers))
1532         (mods-noshift (delq 'shift 
1533                             (copy-sequence idlwave-shell-debug-modifiers))))
1534     (define-key idlwave-mode-map 
1535       (vector (append mods-noshift (list (if shift ?C ?c))))
1536       'idlwave-shell-save-and-run)
1537     (define-key idlwave-mode-map 
1538       (vector (append mods-noshift (list (if shift ?B ?b))))
1539       'idlwave-shell-break-here)
1540     (define-key idlwave-mode-map 
1541       (vector (append mods-noshift (list (if shift ?E ?e))))
1542       'idlwave-shell-run-region)))
1543 (define-key idlwave-mode-map "\C-c\C-d\C-c" 'idlwave-shell-save-and-run)
1544 (define-key idlwave-mode-map "\C-c\C-d\C-b" 'idlwave-shell-break-here)
1545 (define-key idlwave-mode-map "\C-c\C-d\C-e" 'idlwave-shell-run-region)
1546 (define-key idlwave-mode-map "\C-c\C-f" 'idlwave-for)
1547 ;;  (define-key idlwave-mode-map "\C-c\C-f" 'idlwave-function)
1548 ;;  (define-key idlwave-mode-map "\C-c\C-p" 'idlwave-procedure)
1549 (define-key idlwave-mode-map "\C-c\C-r" 'idlwave-repeat)
1550 (define-key idlwave-mode-map "\C-c\C-w" 'idlwave-while)
1551 (define-key idlwave-mode-map "\C-c\C-k" 'idlwave-kill-autoloaded-buffers)
1552 (define-key idlwave-mode-map "\C-c\C-s" 'idlwave-shell)
1553 (define-key idlwave-mode-map "\C-c\C-l" 'idlwave-shell-recenter-shell-window)
1554 (define-key idlwave-mode-map "\C-c\C-b" 'idlwave-list-buffer-load-path-shadows)
1555 (autoload 'idlwave-shell "idlw-shell"
1556   "Run an inferior IDL, with I/O through buffer `(idlwave-shell-buffer)'." t)
1557 (autoload 'idlwave-shell-send-command "idlw-shell")
1558 (autoload 'idlwave-shell-recenter-shell-window "idlw-shell"
1559   "Run `idlwave-shell' and switch back to current window" t)
1560 (autoload 'idlwave-shell-save-and-run "idlw-shell"
1561   "Save and run buffer under the shell." t)
1562 (autoload 'idlwave-shell-break-here "idlw-shell"
1563   "Set breakpoint in current line." t)
1564 (autoload 'idlwave-shell-run-region "idlw-shell"
1565   "Compile and run the region." t)
1566 (define-key idlwave-mode-map "\C-c\C-v"   'idlwave-find-module)
1567 (define-key idlwave-mode-map "\C-c?"      'idlwave-routine-info)
1568 (define-key idlwave-mode-map "\M-?"       'idlwave-context-help)
1569 (define-key idlwave-mode-map [(control meta ?\?)] 'idlwave-online-help)
1570 (define-key idlwave-mode-map [(meta tab)] 'idlwave-complete)
1571 (define-key idlwave-mode-map "\C-c\C-i"   'idlwave-update-routine-info)
1572 (define-key idlwave-mode-map "\C-c="      'idlwave-resolve)
1573 (define-key idlwave-mode-map 
1574   (if (featurep 'xemacs) [(shift button3)] [(shift mouse-3)])
1575   'idlwave-mouse-context-help)
1576
1577 ;; Set action and key bindings.
1578 ;; See description of the function `idlwave-action-and-binding'.
1579 ;; Automatically add spaces for the following characters
1580 (idlwave-action-and-binding "&"  '(idlwave-surround -1 -1))
1581 (idlwave-action-and-binding "<"  '(idlwave-surround -1 -1))
1582 ;; Binding works for both > and ->, by changing the length of the token.
1583 (idlwave-action-and-binding ">"  '(idlwave-surround -1 -1 '(?-) 1 
1584                                                     'idlwave-gtr-pad-hook))
1585 (idlwave-action-and-binding "->" '(idlwave-surround -1 -1 nil 2) t)
1586 (idlwave-action-and-binding ","  '(idlwave-surround 0 -1))
1587 ;; Automatically add spaces to equal sign if not keyword
1588 (idlwave-action-and-binding "="  '(idlwave-expand-equal -1 -1))
1589
1590 ;;;
1591 ;;; Abbrev Section
1592 ;;;
1593 ;;; When expanding abbrevs and the abbrev hook moves backward, an extra
1594 ;;; space is inserted (this is the space typed by the user to expanded
1595 ;;; the abbrev).
1596 ;;;
1597 (defvar idlwave-mode-abbrev-table nil
1598   "Abbreviation table used for IDLWAVE mode")
1599 (define-abbrev-table 'idlwave-mode-abbrev-table ())
1600
1601 (defun idlwave-define-abbrev (name expansion hook &optional noprefix table)
1602   "Define-abbrev with backward compatibility.
1603
1604 If NOPREFIX is non-nil, don't prepend prefix character.  Installs into
1605 idlwave-mode-abbrev-table unless TABLE is non-nil."
1606   (let ((abbrevs-changed nil)  ;; mask the current value to avoid save
1607         (args (list (or table idlwave-mode-abbrev-table)
1608                     (if noprefix name (concat idlwave-abbrev-start-char name))
1609                     expansion
1610                     hook)))
1611     (condition-case nil
1612         (apply 'define-abbrev (append args '(0 t)))
1613       (error (apply 'define-abbrev args)))))
1614
1615 (condition-case nil
1616     (modify-syntax-entry (string-to-char idlwave-abbrev-start-char) 
1617                          "w" idlwave-mode-syntax-table)
1618   (error nil))
1619
1620 ;;
1621 ;; Templates
1622 ;;
1623 (idlwave-define-abbrev "c"   "" (idlwave-code-abbrev idlwave-case))
1624 (idlwave-define-abbrev "sw"  "" (idlwave-code-abbrev idlwave-switch))
1625 (idlwave-define-abbrev "f"   "" (idlwave-code-abbrev idlwave-for))
1626 (idlwave-define-abbrev "fu"  "" (idlwave-code-abbrev idlwave-function))
1627 (idlwave-define-abbrev "pr"  "" (idlwave-code-abbrev idlwave-procedure))
1628 (idlwave-define-abbrev "r"   "" (idlwave-code-abbrev idlwave-repeat))
1629 (idlwave-define-abbrev "w"   "" (idlwave-code-abbrev idlwave-while))
1630 (idlwave-define-abbrev "i"   "" (idlwave-code-abbrev idlwave-if))
1631 (idlwave-define-abbrev "elif" "" (idlwave-code-abbrev idlwave-elif))
1632 ;;
1633 ;; Keywords, system functions, conversion routines
1634 ;;
1635 (idlwave-define-abbrev "ap" "arg_present()" (idlwave-keyword-abbrev 1))
1636 (idlwave-define-abbrev "b"  "begin"        (idlwave-keyword-abbrev 0 t))
1637 (idlwave-define-abbrev "co" "common"       (idlwave-keyword-abbrev 0 t))
1638 (idlwave-define-abbrev "cb" "byte()"       (idlwave-keyword-abbrev 1))
1639 (idlwave-define-abbrev "cx" "fix()"        (idlwave-keyword-abbrev 1))
1640 (idlwave-define-abbrev "cl" "long()"       (idlwave-keyword-abbrev 1))
1641 (idlwave-define-abbrev "cf" "float()"      (idlwave-keyword-abbrev 1))
1642 (idlwave-define-abbrev "cs" "string()"     (idlwave-keyword-abbrev 1))
1643 (idlwave-define-abbrev "cc" "complex()"    (idlwave-keyword-abbrev 1))
1644 (idlwave-define-abbrev "cd" "double()"     (idlwave-keyword-abbrev 1))
1645 (idlwave-define-abbrev "e"  "else"         (idlwave-keyword-abbrev 0 t))
1646 (idlwave-define-abbrev "ec" "endcase"      'idlwave-show-begin)
1647 (idlwave-define-abbrev "es" "endswitch"    'idlwave-show-begin)
1648 (idlwave-define-abbrev "ee" "endelse"      'idlwave-show-begin)
1649 (idlwave-define-abbrev "ef" "endfor"       'idlwave-show-begin)
1650 (idlwave-define-abbrev "ei" "endif else if" 'idlwave-show-begin)
1651 (idlwave-define-abbrev "el" "endif else"   'idlwave-show-begin)
1652 (idlwave-define-abbrev "en" "endif"        'idlwave-show-begin)
1653 (idlwave-define-abbrev "er" "endrep"       'idlwave-show-begin)
1654 (idlwave-define-abbrev "ew" "endwhile"     'idlwave-show-begin)
1655 (idlwave-define-abbrev "g"  "goto,"        (idlwave-keyword-abbrev 0 t))
1656 (idlwave-define-abbrev "h"  "help,"        (idlwave-keyword-abbrev 0))
1657 (idlwave-define-abbrev "k"  "keyword_set()" (idlwave-keyword-abbrev 1))
1658 (idlwave-define-abbrev "n"  "n_elements()" (idlwave-keyword-abbrev 1))
1659 (idlwave-define-abbrev "on" "on_error,"    (idlwave-keyword-abbrev 0))
1660 (idlwave-define-abbrev "oi" "on_ioerror,"  (idlwave-keyword-abbrev 0 1))
1661 (idlwave-define-abbrev "ow" "openw,"       (idlwave-keyword-abbrev 0))
1662 (idlwave-define-abbrev "or" "openr,"       (idlwave-keyword-abbrev 0))
1663 (idlwave-define-abbrev "ou" "openu,"       (idlwave-keyword-abbrev 0))
1664 (idlwave-define-abbrev "p"  "print,"       (idlwave-keyword-abbrev 0))
1665 (idlwave-define-abbrev "pt" "plot,"        (idlwave-keyword-abbrev 0))
1666 (idlwave-define-abbrev "re" "read,"        (idlwave-keyword-abbrev 0))
1667 (idlwave-define-abbrev "rf" "readf,"       (idlwave-keyword-abbrev 0))
1668 (idlwave-define-abbrev "ru" "readu,"       (idlwave-keyword-abbrev 0))
1669 (idlwave-define-abbrev "rt" "return"       (idlwave-keyword-abbrev 0))
1670 (idlwave-define-abbrev "sc" "strcompress()" (idlwave-keyword-abbrev 1))
1671 (idlwave-define-abbrev "sn" "strlen()"     (idlwave-keyword-abbrev 1))
1672 (idlwave-define-abbrev "sl" "strlowcase()" (idlwave-keyword-abbrev 1))
1673 (idlwave-define-abbrev "su" "strupcase()"  (idlwave-keyword-abbrev 1))
1674 (idlwave-define-abbrev "sm" "strmid()"     (idlwave-keyword-abbrev 1))
1675 (idlwave-define-abbrev "sp" "strpos()"     (idlwave-keyword-abbrev 1))
1676 (idlwave-define-abbrev "st" "strput()"     (idlwave-keyword-abbrev 1))
1677 (idlwave-define-abbrev "sr" "strtrim()"    (idlwave-keyword-abbrev 1))
1678 (idlwave-define-abbrev "t"  "then"         (idlwave-keyword-abbrev 0 t))
1679 (idlwave-define-abbrev "u"  "until"        (idlwave-keyword-abbrev 0 t))
1680 (idlwave-define-abbrev "wu" "writeu,"      (idlwave-keyword-abbrev 0))
1681 (idlwave-define-abbrev "iap" "if arg_present() then"     (idlwave-keyword-abbrev 6))
1682 (idlwave-define-abbrev "ik" "if keyword_set() then" (idlwave-keyword-abbrev 6))
1683 (idlwave-define-abbrev "ine" "if n_elements() eq 0 then" (idlwave-keyword-abbrev 11))
1684 (idlwave-define-abbrev "inn" "if n_elements() ne 0 then" (idlwave-keyword-abbrev 11))
1685 (idlwave-define-abbrev "np" "n_params()"   (idlwave-keyword-abbrev 0))
1686 (idlwave-define-abbrev "s"  "size()"       (idlwave-keyword-abbrev 1))
1687 (idlwave-define-abbrev "wi" "widget_info()" (idlwave-keyword-abbrev 1))
1688 (idlwave-define-abbrev "wc" "widget_control," (idlwave-keyword-abbrev 0))
1689   
1690 ;; This section is reserved words only. (From IDL user manual)
1691 ;;
1692 (idlwave-define-abbrev "and"        "and"       (idlwave-keyword-abbrev 0 t) t)
1693 (idlwave-define-abbrev "begin"      "begin"     (idlwave-keyword-abbrev 0 t) t)
1694 (idlwave-define-abbrev "break"      "break"     (idlwave-keyword-abbrev 0 t) t)
1695 (idlwave-define-abbrev "case"       "case"      (idlwave-keyword-abbrev 0 t) t)
1696 (idlwave-define-abbrev "common"     "common"    (idlwave-keyword-abbrev 0 t) t)
1697 (idlwave-define-abbrev "continue"   "continue"  (idlwave-keyword-abbrev 0 t) t)
1698 (idlwave-define-abbrev "do"         "do"        (idlwave-keyword-abbrev 0 t) t)
1699 (idlwave-define-abbrev "else"       "else"      (idlwave-keyword-abbrev 0 t) t)
1700 (idlwave-define-abbrev "end"        "end"       'idlwave-show-begin-check t)
1701 (idlwave-define-abbrev "endcase"    "endcase"   'idlwave-show-begin-check t)
1702 (idlwave-define-abbrev "endelse"    "endelse"   'idlwave-show-begin-check t)
1703 (idlwave-define-abbrev "endfor"     "endfor"    'idlwave-show-begin-check t)
1704 (idlwave-define-abbrev "endif"      "endif"     'idlwave-show-begin-check t)
1705 (idlwave-define-abbrev "endrep"     "endrep"    'idlwave-show-begin-check t)
1706 (idlwave-define-abbrev "endswitch"  "endswitch" 'idlwave-show-begin-check t)
1707 (idlwave-define-abbrev "endwhi"     "endwhi"    'idlwave-show-begin-check t)
1708 (idlwave-define-abbrev "endwhile"   "endwhile"  'idlwave-show-begin-check t)
1709 (idlwave-define-abbrev "eq"         "eq"        (idlwave-keyword-abbrev 0 t) t)
1710 (idlwave-define-abbrev "for"        "for"       (idlwave-keyword-abbrev 0 t) t)
1711 (idlwave-define-abbrev "function"   "function"  (idlwave-keyword-abbrev 0 t) t)
1712 (idlwave-define-abbrev "ge"         "ge"        (idlwave-keyword-abbrev 0 t) t)
1713 (idlwave-define-abbrev "goto"       "goto"      (idlwave-keyword-abbrev 0 t) t)
1714 (idlwave-define-abbrev "gt"         "gt"        (idlwave-keyword-abbrev 0 t) t)
1715 (idlwave-define-abbrev "if"         "if"        (idlwave-keyword-abbrev 0 t) t)
1716 (idlwave-define-abbrev "le"         "le"        (idlwave-keyword-abbrev 0 t) t)
1717 (idlwave-define-abbrev "lt"         "lt"        (idlwave-keyword-abbrev 0 t) t)
1718 (idlwave-define-abbrev "mod"        "mod"       (idlwave-keyword-abbrev 0 t) t)
1719 (idlwave-define-abbrev "ne"         "ne"        (idlwave-keyword-abbrev 0 t) t)
1720 (idlwave-define-abbrev "not"        "not"       (idlwave-keyword-abbrev 0 t) t)
1721 (idlwave-define-abbrev "of"         "of"        (idlwave-keyword-abbrev 0 t) t)
1722 (idlwave-define-abbrev "on_ioerror" "on_ioerror" (idlwave-keyword-abbrev 0 t) t)
1723 (idlwave-define-abbrev "or"         "or"        (idlwave-keyword-abbrev 0 t) t)
1724 (idlwave-define-abbrev "pro"        "pro"       (idlwave-keyword-abbrev 0 t) t)
1725 (idlwave-define-abbrev "repeat"     "repeat"    (idlwave-keyword-abbrev 0 t) t)
1726 (idlwave-define-abbrev "switch"     "switch"    (idlwave-keyword-abbrev 0 t) t)
1727 (idlwave-define-abbrev "then"       "then"      (idlwave-keyword-abbrev 0 t) t)
1728 (idlwave-define-abbrev "until"      "until"     (idlwave-keyword-abbrev 0 t) t)
1729 (idlwave-define-abbrev "while"      "while"     (idlwave-keyword-abbrev 0 t) t)
1730 (idlwave-define-abbrev "xor"        "xor"       (idlwave-keyword-abbrev 0 t) t)
1731
1732 (defvar imenu-create-index-function)
1733 (defvar extract-index-name-function)
1734 (defvar prev-index-position-function)
1735 (defvar imenu-extract-index-name-function)
1736 (defvar imenu-prev-index-position-function)
1737 ;; defined later - so just make the compiler hush
1738 (defvar idlwave-mode-menu)  
1739 (defvar idlwave-mode-debug-menu)
1740
1741 ;;;###autoload
1742 (defun idlwave-mode ()
1743   "Major mode for editing IDL source files (version 5.1).
1744
1745 The main features of this mode are
1746
1747 1. Indentation and Formatting
1748    --------------------------
1749    Like other Emacs programming modes, C-j inserts a newline and indents.
1750    TAB is used for explicit indentation of the current line.
1751
1752    To start a continuation line, use \\[idlwave-split-line].  This
1753    function can also be used in the middle of a line to split the line
1754    at that point.  When used inside a long constant string, the string
1755    is split at that point with the `+' concatenation operator.
1756
1757    Comments are indented as follows:
1758
1759    `;;;' Indentation remains unchanged.
1760    `;;'  Indent like the surrounding code
1761    `;'   Indent to a minimum column.
1762
1763    The indentation of comments starting in column 0 is never changed.
1764
1765    Use \\[idlwave-fill-paragraph] to refill a paragraph inside a
1766    comment.  The indentation of the second line of the paragraph
1767    relative to the first will be retained.  Use
1768    \\[idlwave-auto-fill-mode] to toggle auto-fill mode for these
1769    comments.  When the variable `idlwave-fill-comment-line-only' is
1770    nil, code can also be auto-filled and auto-indented (not
1771    recommended).
1772
1773    To convert pre-existing IDL code to your formatting style, mark the
1774    entire buffer with \\[mark-whole-buffer] and execute
1775    \\[idlwave-expand-region-abbrevs].  Then mark the entire buffer
1776    again followed by \\[indent-region] (`indent-region').
1777
1778 2. Routine Info
1779    ------------
1780    IDLWAVE displays information about the calling sequence and the
1781    accepted keyword parameters of a procedure or function with
1782    \\[idlwave-routine-info].  \\[idlwave-find-module] jumps to the
1783    source file of a module.  These commands know about system
1784    routines, all routines in idlwave-mode buffers and (when the
1785    idlwave-shell is active) about all modules currently compiled under
1786    this shell.  Use \\[idlwave-update-routine-info] to update this
1787    information, which is also used for completion (see item 4).
1788
1789 3. Online IDL Help
1790    ---------------
1791    \\[idlwave-context-help] displays the IDL documentation relevant
1792    for the system variable, keyword, or routine at point.  A single key
1793    stroke gets you directly to the right place in the docs.  Two additional
1794    files (an ASCII version of the IDL documentation and a topics file) must
1795    be installed for this - check the IDLWAVE webpage for these files.
1796
1797 4. Completion
1798    ----------
1799    \\[idlwave-complete] completes the names of procedures, functions
1800    class names and keyword parameters.  It is context sensitive and
1801    figures out what is expected at point (procedure/function/keyword).
1802    Lower case strings are completed in lower case, other strings in
1803    mixed or upper case.
1804
1805 5. Code Templates and Abbreviations
1806    --------------------------------
1807    Many Abbreviations are predefined to expand to code fragments and templates.
1808    The abbreviations start generally with a `\\`.  Some examples
1809
1810    \\pr        PROCEDURE template
1811    \\fu        FUNCTION template
1812    \\c         CASE statement template
1813    \\sw        SWITCH statement template
1814    \\f         FOR loop template
1815    \\r         REPEAT Loop template
1816    \\w         WHILE loop template
1817    \\i         IF statement template
1818    \\elif      IF-ELSE statement template
1819    \\b         BEGIN
1820    
1821    For a full list, use \\[idlwave-list-abbrevs].  Some templates also have
1822    direct keybindings - see the list of keybindings below.
1823
1824    \\[idlwave-doc-header] inserts a documentation header at the beginning of the
1825    current program unit (pro, function or main).  Change log entries
1826    can be added to the current program unit with \\[idlwave-doc-modification].
1827
1828 6. Automatic Case Conversion
1829    -------------------------
1830    The case of reserved words and some abbrevs is controlled by
1831    `idlwave-reserved-word-upcase' and `idlwave-abbrev-change-case'.
1832
1833 7. Automatic END completion
1834    ------------------------
1835    If the variable `idlwave-expand-generic-end' is non-nil, each END typed
1836    will be converted to the specific version, like ENDIF, ENDFOR, etc.
1837
1838 8. Hooks
1839    -----
1840    Loading idlwave.el runs `idlwave-load-hook'.
1841    Turning on `idlwave-mode' runs `idlwave-mode-hook'.
1842
1843 9. Documentation and Customization
1844    -------------------------------
1845    Info documentation for this package is available.  Use
1846    \\[idlwave-info] to display (complain to your sysadmin if that does
1847    not work).  For Postscript, PDF, and HTML versions of the
1848    documentation, check IDLWAVE's homepage at `http://idlwave.org'.
1849    IDLWAVE has customize support - see the group `idlwave'.
1850
1851 10.Keybindings
1852    -----------
1853    Here is a list of all keybindings of this mode.
1854    If some of the key bindings below show with ??, use \\[describe-key]
1855    followed by the key sequence to see what the key sequence does.
1856
1857 \\{idlwave-mode-map}"
1858
1859   (interactive)
1860   (kill-all-local-variables)
1861   
1862   (if idlwave-startup-message
1863       (message "Emacs IDLWAVE mode version %s." idlwave-mode-version))
1864   (setq idlwave-startup-message nil)
1865   
1866   (setq local-abbrev-table idlwave-mode-abbrev-table)
1867   (set-syntax-table idlwave-mode-syntax-table)
1868   
1869   (set (make-local-variable 'indent-line-function) 'idlwave-indent-and-action)
1870   
1871   (make-local-variable idlwave-comment-indent-function)
1872   (set idlwave-comment-indent-function 'idlwave-comment-hook)
1873   
1874   (set (make-local-variable 'comment-start-skip) ";+[ \t]*")
1875   (set (make-local-variable 'comment-start) ";")
1876   (set (make-local-variable 'require-final-newline) t)
1877   (set (make-local-variable 'abbrev-all-caps) t)
1878   (set (make-local-variable 'indent-tabs-mode) nil)
1879   (set (make-local-variable 'completion-ignore-case) t)
1880   
1881   (use-local-map idlwave-mode-map)
1882
1883   (when (featurep 'easymenu)
1884     (easy-menu-add idlwave-mode-menu idlwave-mode-map)
1885     (easy-menu-add idlwave-mode-debug-menu idlwave-mode-map))
1886
1887   (setq mode-name "IDLWAVE")
1888   (setq major-mode 'idlwave-mode)
1889   (setq abbrev-mode t)
1890   
1891   (set (make-local-variable idlwave-fill-function) 'idlwave-auto-fill)
1892   (setq comment-end "")
1893   (set (make-local-variable 'comment-multi-line) nil)
1894   (set (make-local-variable 'paragraph-separate) 
1895        "[ \t\f]*$\\|[ \t]*;+[ \t]*$\\|;+[+=-_*]+$")
1896   (set (make-local-variable 'paragraph-start) "[ \t\f]\\|[ \t]*;+[ \t]")
1897   (set (make-local-variable 'paragraph-ignore-fill-prefix) nil)
1898   (set (make-local-variable 'parse-sexp-ignore-comments) t)
1899   
1900   ;; Set tag table list to use IDLTAGS as file name.
1901   (if (boundp 'tag-table-alist)
1902       (add-to-list 'tag-table-alist '("\\.pro$" . "IDLTAGS")))
1903   
1904   ;; Font-lock additions - originally Phil Williams, then Ulrik Dickow
1905   ;; Following line is for Emacs - XEmacs uses the corresponding property
1906   ;; on the `idlwave-mode' symbol.
1907   (set (make-local-variable 'font-lock-defaults) idlwave-font-lock-defaults)
1908
1909   ;; Imenu setup
1910   (set (make-local-variable 'imenu-create-index-function)
1911        'imenu-default-create-index-function)
1912   (set (make-local-variable 'imenu-extract-index-name-function)
1913        'idlwave-unit-name)
1914   (set (make-local-variable 'imenu-prev-index-position-function)
1915        'idlwave-prev-index-position)
1916
1917   ;; Make a local post-command-hook and add our hook to it
1918   ;; NB: `make-local-hook' needed for older/alternative Emacs compatibility
1919   (make-local-hook 'post-command-hook)
1920   (add-hook 'post-command-hook 'idlwave-command-hook nil 'local)
1921
1922   ;; Make local hooks for buffer updates
1923   ;; NB: `make-local-hook' needed for older/alternative Emacs compatibility
1924   (make-local-hook 'kill-buffer-hook)
1925   (add-hook 'kill-buffer-hook 'idlwave-kill-buffer-update nil 'local)
1926   (make-local-hook 'after-save-hook)
1927   (add-hook 'after-save-hook 'idlwave-save-buffer-update nil 'local)
1928   (add-hook 'after-save-hook 'idlwave-revoke-license-to-kill nil 'local)
1929
1930   ;; Setup directories and file, if necessary
1931   (idlwave-setup)
1932
1933   ;; Update the routine info with info about current buffer?
1934   (idlwave-new-buffer-update)
1935
1936   ;; Run the mode hook
1937   (run-hooks 'idlwave-mode-hook))
1938
1939 (defvar idlwave-setup-done nil)
1940 (defun idlwave-setup ()
1941   (unless idlwave-setup-done
1942     (if (not (file-directory-p idlwave-config-directory))
1943         (make-directory idlwave-config-directory))
1944     (setq idlwave-user-catalog-file (expand-file-name 
1945                                      idlwave-user-catalog-file 
1946                                      idlwave-config-directory)
1947         idlwave-path-file (expand-file-name 
1948                            idlwave-path-file 
1949                            idlwave-config-directory))
1950     (idlwave-read-paths)  ; we may need these early
1951     (setq idlwave-setup-done t)))
1952
1953 ;;
1954 ;; Code Formatting ----------------------------------------------------
1955 ;; 
1956
1957 (defun idlwave-push-mark (&rest rest)
1958   "Push mark for compatibility with Emacs 18/19."
1959   (if (fboundp 'iconify-frame)
1960       (apply 'push-mark rest)
1961     (push-mark)))
1962
1963 (defun idlwave-hard-tab ()
1964   "Inserts TAB in buffer in current position."
1965   (interactive)
1966   (insert "\t"))
1967
1968 ;;; This stuff is experimental
1969
1970 (defvar idlwave-command-hook nil
1971   "If non-nil, a list that can be evaluated using `eval'.
1972 It is evaluated in the lisp function `idlwave-command-hook' which is
1973 placed in `post-command-hook'.")
1974
1975 (defun idlwave-command-hook ()
1976   "Command run after every command.
1977 Evaluates a non-nil value of the *variable* `idlwave-command-hook' and
1978 sets the variable to zero afterwards."
1979   (and idlwave-command-hook
1980        (listp idlwave-command-hook)
1981        (condition-case nil
1982            (eval idlwave-command-hook)
1983          (error nil)))
1984   (setq idlwave-command-hook nil))
1985
1986 ;;; End experiment
1987
1988 ;; It would be better to use expand.el for better abbrev handling and
1989 ;; versatility.
1990
1991 (defun idlwave-check-abbrev (arg &optional reserved)
1992   "Reverses abbrev expansion if in comment or string.
1993 Argument ARG is the number of characters to move point
1994 backward if `idlwave-abbrev-move' is non-nil.
1995 If optional argument RESERVED is non-nil then the expansion
1996 consists of reserved words, which will be capitalized if
1997 `idlwave-reserved-word-upcase' is non-nil.
1998 Otherwise, the abbrev will be capitalized if `idlwave-abbrev-change-case'
1999 is non-nil, unless its value is \`down in which case the abbrev will be
2000 made into all lowercase.
2001 Returns non-nil if abbrev is left expanded."
2002   (if (idlwave-quoted)
2003       (progn (unexpand-abbrev)
2004              nil)
2005     (if (and reserved idlwave-reserved-word-upcase)
2006         (upcase-region last-abbrev-location (point))
2007       (cond
2008        ((equal idlwave-abbrev-change-case 'down)
2009         (downcase-region last-abbrev-location (point)))
2010        (idlwave-abbrev-change-case
2011         (upcase-region last-abbrev-location (point)))))
2012     (if (and idlwave-abbrev-move (> arg 0))
2013         (if (boundp 'post-command-hook)
2014             (setq idlwave-command-hook (list 'backward-char (1+ arg)))
2015           (backward-char arg)))
2016     t))
2017
2018 (defun idlwave-in-comment ()
2019   "Returns t if point is inside a comment, nil otherwise."
2020   (save-excursion
2021     (let ((here (point)))
2022       (and (idlwave-goto-comment) (> here (point))))))
2023
2024 (defun idlwave-goto-comment ()
2025   "Move to start of comment delimiter on current line.
2026 Moves to end of line if there is no comment delimiter.
2027 Ignores comment delimiters in strings.
2028 Returns point if comment found and nil otherwise."
2029   (let ((eos (progn (end-of-line) (point)))
2030         (data (match-data))
2031         found)
2032     ;; Look for first comment delimiter not in a string
2033     (beginning-of-line)
2034     (setq found (search-forward comment-start eos 'lim))
2035     (while (and found (idlwave-in-quote))
2036       (setq found (search-forward comment-start eos 'lim)))
2037     (store-match-data data)
2038     (and found (not (idlwave-in-quote))
2039          (progn
2040            (backward-char 1)
2041            (point)))))
2042
2043 (defvar transient-mark-mode)
2044 (defvar zmacs-regions)
2045 (defvar mark-active)
2046 (defun idlwave-region-active-p ()
2047   "Is transient-mark-mode on and the region active?
2048 Works on both Emacs and XEmacs."
2049   (if (featurep 'xemacs)
2050       (and zmacs-regions (region-active-p))
2051     (and transient-mark-mode mark-active)))
2052
2053 (defun idlwave-show-matching-quote ()
2054   "Insert quote and show matching quote if this is end of a string."
2055   (interactive)
2056   (let ((bq (idlwave-in-quote))
2057         (inq last-command-char))
2058     (if (and bq (not (idlwave-in-comment)))
2059         (let ((delim (char-after bq)))
2060           (insert inq)
2061           (if (eq inq delim)
2062               (save-excursion
2063                 (goto-char bq)
2064                 (sit-for 1))))
2065       ;; Not the end of a string
2066       (insert inq))))
2067
2068 (defun idlwave-show-begin-check ()
2069   "Ensure that the previous word was a token before `idlwave-show-begin'.
2070 An END token must be preceded by whitespace."
2071   (if (not (idlwave-quoted))
2072       (if
2073           (save-excursion
2074             (backward-word 1)
2075             (backward-char 1)
2076             (looking-at "[ \t\n\f]"))
2077           (idlwave-show-begin))))
2078
2079 (defun idlwave-show-begin ()
2080   "Finds the start of current block and blinks to it for a second.
2081 Also checks if the correct end statement has been used."
2082   ;; All end statements are reserved words
2083   ;; Re-indent end line
2084   (insert-char ?\  1) ;; So indent, etc. work well
2085   (backward-char 1)
2086   (let* ((pos (point-marker))
2087          (last-abbrev-marker (copy-marker last-abbrev-location))
2088          (eol-pos (save-excursion (end-of-line) (point)))
2089          begin-pos end-pos end end1 )
2090     (if idlwave-reindent-end  (idlwave-indent-line))
2091     (setq last-abbrev-location (marker-position last-abbrev-marker))
2092     (when (and (idlwave-check-abbrev 0 t)
2093                idlwave-show-block)
2094       (save-excursion
2095         ;; Move inside current block
2096         (goto-char last-abbrev-marker)
2097         (idlwave-block-jump-out -1 'nomark)
2098         (setq begin-pos (point))
2099         (idlwave-block-jump-out 1 'nomark)
2100         (setq end-pos (point))
2101         (if (> end-pos eol-pos)
2102             (setq end-pos pos))
2103         (goto-char end-pos)
2104         (setq end (buffer-substring 
2105                    (progn
2106                      (skip-chars-backward "a-zA-Z")
2107                      (point))
2108                    end-pos))
2109         (goto-char begin-pos)
2110         (when (setq end1 (cdr (idlwave-block-master)))
2111           (cond
2112            ((null end1)) ; no-operation
2113            ((string= (downcase end) (downcase end1))
2114             (sit-for 1))
2115            ((string= (downcase end) "end")
2116             ;; A generic end
2117             (if idlwave-expand-generic-end
2118                 (save-excursion
2119                   (goto-char pos)
2120                   (backward-char 3)
2121                   (insert (if (string= end "END") (upcase end1) end1))
2122                   (delete-char 3)))
2123             (sit-for 1))
2124            (t
2125             (beep)
2126             (message "Warning: Shouldn't this be \"%s\" instead of \"%s\"?" 
2127                      end1 end)
2128             (sit-for 1)))))))
2129   (delete-char 1))
2130
2131 (defun idlwave-block-master ()
2132   (let ((case-fold-search t))
2133     (save-excursion
2134       (cond
2135        ((looking-at "pro\\|case\\|switch\\|function\\>")
2136         (assoc (downcase (match-string 0)) idlwave-block-matches))
2137        ((looking-at "begin\\>")
2138         (let ((limit (save-excursion 
2139                        (idlwave-beginning-of-statement) 
2140                        (point))))
2141           (cond
2142            ((re-search-backward ":[ \t]*\\=" limit t)
2143             ;; seems to be a case thing
2144             '("begin" . "end"))
2145            ((re-search-backward idlwave-block-match-regexp limit t)
2146             (assoc (downcase (match-string 1))
2147                    idlwave-block-matches))
2148            (t
2149             ;; Just a nromal block
2150             '("begin" . "end")))))
2151        (t nil)))))
2152
2153 (defun idlwave-close-block ()
2154   "Terminate the current block with the correct END statement."
2155   (interactive)
2156
2157   ;; Start new line if we are not in a new line
2158   (unless (save-excursion
2159             (skip-chars-backward " \t")
2160             (bolp))
2161     (let ((idlwave-show-block nil))
2162       (newline-and-indent)))
2163   (let ((last-abbrev-location (point)))  ; for upcasing
2164     (insert "end")
2165     (idlwave-show-begin)))
2166
2167 (defun idlwave-gtr-pad-hook (char) 
2168   "Let the > symbol expand around -> if present.  The new token length
2169 is returned."  
2170   2)
2171
2172 (defun idlwave-surround (&optional before after escape-chars length ec-hook)
2173   "Surround the LENGTH characters before point with blanks.
2174 LENGTH defaults to 1.
2175 Optional arguments BEFORE and AFTER affect the behavior before and
2176 after the characters (see also description of `idlwave-make-space'):
2177
2178 nil            do nothing
2179 0              force no spaces
2180 integer > 0    force exactly n spaces
2181 integer < 0    at least |n| spaces
2182
2183 The function does nothing if any of the following conditions is true:
2184 - `idlwave-surround-by-blank' is nil
2185 - the character before point is inside a string or comment
2186 - the char preceeding the string to be surrounded is a member of ESCAPE-CHARS.
2187   This hack is used to avoid padding of `>' when it is part of
2188   the '->' operator.  In this case, ESCAPE-CHARS would be '(?-).
2189
2190 If a function is passed in EC-HOOK, and an ESCAPE-CHARS match occurs,
2191 the named function will be called with a single argument of the
2192 preceeding character.  Then idlwave-surround will run as usual if
2193 EC-HOOK returns non-nil, and a new length will be taken from the
2194 return value."
2195   (when (and idlwave-surround-by-blank (not (idlwave-quoted)))
2196     (let* ((length (or length 1)) ; establish a default for LENGTH
2197            (prev-char (char-after (- (point) (1+ length)))))
2198       (when (or (not (memq prev-char escape-chars))
2199                 (and (fboundp ec-hook) 
2200                      (setq length 
2201                            (save-excursion (funcall ec-hook prev-char)))))
2202         (backward-char length)
2203         (save-restriction
2204           (let ((here (point)))
2205             (skip-chars-backward " \t")
2206             (if (bolp)
2207                 ;; avoid clobbering indent
2208                 (progn
2209                   (move-to-column (idlwave-calculate-indent))
2210                   (if (<= (point) here)
2211                       (narrow-to-region (point) here))
2212                   (goto-char here)))
2213             (idlwave-make-space before))
2214           (skip-chars-forward " \t"))
2215         (forward-char length)
2216         (idlwave-make-space after)
2217         ;; Check to see if the line should auto wrap
2218         (if (and (equal (char-after (1- (point))) ?\ )
2219                  (> (current-column) fill-column))
2220             (funcall auto-fill-function))))))
2221
2222 (defun idlwave-make-space (n)
2223   "Make space at point.
2224 The space affected is all the spaces and tabs around point.
2225 If n is non-nil then point is left abs(n) spaces from the beginning of
2226 the contiguous space.
2227 The amount of space at point is determined by N.
2228 If the value of N is:
2229 nil   - do nothing.
2230 > 0   - exactly N spaces.
2231 < 0   - a minimum of -N spaces, i.e., do not change if there are
2232         already -N spaces.
2233 0     - no spaces (i.e. remove any existing space)."
2234   (if (integerp n)
2235       (let
2236           ((start-col (progn (skip-chars-backward " \t") (current-column)))
2237            (left (point))
2238            (end-col (progn (skip-chars-forward " \t") (current-column))))
2239         (delete-horizontal-space)
2240         (cond
2241          ((> n 0)
2242           (idlwave-indent-to (+ start-col n))
2243           (goto-char (+ left n)))
2244          ((< n 0)
2245           (idlwave-indent-to end-col (- n))
2246           (goto-char (- left n)))
2247          ;; n = 0, done
2248          ))))
2249
2250 (defun idlwave-newline ()
2251   "Inserts a newline and indents the current and previous line."
2252   (interactive)
2253   ;;
2254   ;; Handle unterminated single and double quotes
2255   ;; If not in a comment and in a string then insertion of a newline
2256   ;; will mean unbalanced quotes.
2257   ;;
2258   (if (and (not (idlwave-in-comment)) (idlwave-in-quote))
2259       (progn (beep)
2260              (message "Warning: unbalanced quotes?")))
2261   (newline)
2262   ;;
2263   ;; The current line is being split, the cursor should be at the
2264   ;; beginning of the new line skipping the leading indentation.
2265   ;;
2266   ;; The reason we insert the new line before indenting is that the
2267   ;; indenting could be confused by keywords (e.g. END) on the line
2268   ;; after the split point.  This prevents us from just using
2269   ;; `indent-for-tab-command' followed by `newline-and-indent'.
2270   ;;
2271   (beginning-of-line 0)
2272   (idlwave-indent-line)
2273   (forward-line)
2274   (idlwave-indent-line))
2275
2276 ;;
2277 ;;  Use global variable 'comment-column' to set parallel comment
2278 ;;
2279 ;; Modeled on lisp.el
2280 ;; Emacs Lisp and IDL (Wave CL) have identical comment syntax
2281 (defun idlwave-comment-hook ()
2282   "Compute indent for the beginning of the IDL comment delimiter."
2283   (if (or (looking-at idlwave-no-change-comment)
2284           (if idlwave-begin-line-comment
2285               (looking-at idlwave-begin-line-comment)
2286             (looking-at "^;")))
2287       (current-column)
2288     (if (looking-at idlwave-code-comment)
2289         (if (save-excursion (skip-chars-backward " \t") (bolp))
2290             ;; On line by itself, indent as code
2291             (let ((tem (idlwave-calculate-indent)))
2292               (if (listp tem) (car tem) tem))
2293           ;; after code - do not change
2294           (current-column))
2295       (skip-chars-backward " \t")
2296       (max (if (bolp) 0 (1+ (current-column)))
2297            comment-column))))
2298
2299 (defun idlwave-split-line ()
2300   "Continue line by breaking line at point and indent the lines.
2301 For a code line insert continuation marker. If the line is a line comment
2302 then the new line will contain a comment with the same indentation.
2303 Splits strings with the IDL operator `+' if `idlwave-split-line-string' is
2304 non-nil."
2305   (interactive)
2306   ;; Expand abbreviation, just like normal RET would.
2307   (and abbrev-mode (expand-abbrev))
2308   (let (beg)
2309     (if (not (idlwave-in-comment))
2310         ;; For code line add continuation.
2311         ;; Check if splitting a string.
2312         (progn
2313           (if (setq beg (idlwave-in-quote))
2314               (if idlwave-split-line-string
2315                   ;; Split the string.
2316                   (progn (insert (setq beg (char-after beg)) " + "
2317                                  idlwave-continuation-char beg)
2318                          (backward-char 1)
2319                          (newline-and-indent)
2320                          (forward-char 1))
2321                 ;; Do not split the string.
2322                 (beep)
2323                 (message "Warning: continuation inside string!!")
2324                 (insert " " idlwave-continuation-char))
2325             ;; Not splitting a string.
2326             (if (not (member (char-before) '(?\  ?\t)))
2327                 (insert " "))
2328             (insert idlwave-continuation-char)
2329             (newline-and-indent)))
2330       (indent-new-comment-line))
2331     ;; Indent previous line
2332     (setq beg (- (point-max) (point)))
2333     (forward-line -1)
2334     (idlwave-indent-line)
2335     (goto-char (- (point-max) beg))
2336     ;; Reindent new line
2337     (idlwave-indent-line)))
2338
2339 (defun idlwave-beginning-of-subprogram ()
2340   "Moves point to the beginning of the current program unit."
2341   (interactive)
2342   (idlwave-find-key idlwave-begin-unit-reg -1))
2343
2344 (defun idlwave-end-of-subprogram ()
2345   "Moves point to the start of the next program unit."
2346   (interactive)
2347   (idlwave-end-of-statement)
2348   (idlwave-find-key idlwave-end-unit-reg 1))
2349
2350 (defun idlwave-mark-statement ()
2351   "Mark current IDL statement."
2352   (interactive)
2353   (idlwave-end-of-statement)
2354   (let ((end (point)))
2355     (idlwave-beginning-of-statement)
2356     (idlwave-push-mark end nil t)))
2357
2358 (defun idlwave-mark-block ()
2359   "Mark containing block."
2360   (interactive)
2361   (idlwave-end-of-statement)
2362   (idlwave-backward-up-block -1)
2363   (idlwave-end-of-statement)
2364   (let ((end (point)))
2365     (idlwave-backward-block)
2366     (idlwave-beginning-of-statement)
2367     (idlwave-push-mark end nil t)))
2368
2369
2370 (defun idlwave-mark-subprogram ()
2371   "Put mark at beginning of program, point at end.
2372 The marks are pushed."
2373   (interactive)
2374   (idlwave-end-of-statement)
2375   (idlwave-beginning-of-subprogram)
2376   (let ((beg (point)))
2377     (idlwave-forward-block)
2378     (idlwave-push-mark beg nil t))
2379   (exchange-point-and-mark))
2380
2381 (defun idlwave-backward-up-block (&optional arg)
2382   "Move to beginning of enclosing block if prefix ARG >= 0.
2383 If prefix ARG < 0 then move forward to enclosing block end."
2384   (interactive "p")
2385   (idlwave-block-jump-out (- arg) 'nomark))
2386
2387 (defun idlwave-beginning-of-block ()
2388   "Go to the beginning of the current block."
2389   (interactive)
2390   (idlwave-block-jump-out -1 'nomark)
2391   (forward-word 1))
2392
2393 (defun idlwave-end-of-block ()
2394   "Go to the beginning of the current block."
2395   (interactive)
2396   (idlwave-block-jump-out 1 'nomark)
2397   (backward-word 1))
2398
2399 (defun idlwave-forward-block ()
2400   "Move across next nested block."
2401   (interactive)
2402   (if (idlwave-down-block 1)
2403       (idlwave-block-jump-out 1 'nomark)))
2404
2405 (defun idlwave-backward-block ()
2406   "Move backward across previous nested block."
2407   (interactive)
2408   (if (idlwave-down-block -1)
2409       (idlwave-block-jump-out -1 'nomark)))
2410
2411 (defun idlwave-down-block (&optional arg)
2412   "Go down a block.
2413 With ARG: ARG >= 0 go forwards, ARG < 0 go backwards.
2414 Returns non-nil if successfull."
2415   (interactive "p")
2416   (let (status)
2417     (if (< arg 0)
2418         ;; Backward
2419         (let ((eos (save-excursion
2420                      (idlwave-block-jump-out -1 'nomark)
2421                      (point))))
2422           (if (setq status (idlwave-find-key 
2423                             idlwave-end-block-reg -1 'nomark eos))
2424               (idlwave-beginning-of-statement)
2425             (message "No nested block before beginning of containing block.")))
2426       ;; Forward
2427       (let ((eos (save-excursion
2428                    (idlwave-block-jump-out 1 'nomark)
2429                    (point))))
2430         (if (setq status (idlwave-find-key 
2431                           idlwave-begin-block-reg 1 'nomark eos))
2432             (idlwave-end-of-statement)
2433           (message "No nested block before end of containing block."))))
2434     status))
2435
2436 (defun idlwave-mark-doclib ()
2437   "Put point at beginning of doc library header, mark at end.
2438 The marks are pushed."
2439   (interactive)
2440   (let (beg
2441         (here (point)))
2442     (goto-char (point-max))
2443     (if (re-search-backward idlwave-doclib-start nil t)
2444         (progn 
2445           (setq beg (progn (beginning-of-line) (point)))
2446           (if (re-search-forward idlwave-doclib-end nil t)
2447               (progn
2448                 (forward-line 1)
2449                 (idlwave-push-mark beg nil t)
2450                 (message "Could not find end of doc library header.")))
2451           (message "Could not find doc library header start.")
2452           (goto-char here)))))
2453
2454
2455 (defun idlwave-current-routine ()
2456   "Return (NAME TYPE CLASS) of current routine."
2457   (idlwave-routines)
2458   (save-excursion
2459     (idlwave-beginning-of-subprogram)
2460     (if (looking-at "[ \t]*\\<\\(pro\\|function\\)\\>\\s-+\\(\\([a-zA-Z0-9$_]+\\)::\\)?\\([a-zA-Z0-9$_]+\\)")
2461         (let* ((type (if (string= (downcase (match-string 1)) "pro")
2462                          'pro 'function))
2463                (class (idlwave-sintern-class (match-string 3)))
2464                (name (idlwave-sintern-routine-or-method (match-string 4) class)))
2465           (list name type class)))))
2466
2467 (defvar idlwave-shell-prompt-pattern)
2468 (defun idlwave-beginning-of-statement ()
2469   "Move to beginning of the current statement.
2470 Skips back past statement continuations.
2471 Point is placed at the beginning of the line whether or not this is an
2472 actual statement."
2473   (interactive)
2474   (cond
2475    ((eq major-mode 'idlwave-shell-mode)
2476     (if (re-search-backward idlwave-shell-prompt-pattern nil t)
2477         (goto-char (match-end 0))))
2478    (t   
2479     (if (save-excursion (forward-line -1) (idlwave-is-continuation-line))
2480         (idlwave-previous-statement)
2481       (beginning-of-line)))))
2482
2483 (defun idlwave-previous-statement ()
2484   "Moves point to beginning of the previous statement.
2485 Returns t if the current line before moving is the beginning of
2486 the first non-comment statement in the file, and nil otherwise."
2487   (interactive)
2488   (let (first-statement)
2489     (if (not (= (forward-line -1) 0))
2490         ;; first line in file
2491         t
2492       ;; skip blank lines, label lines, include lines and line comments
2493       (while (and
2494               ;; The current statement is the first statement until we
2495               ;; reach another statement.
2496               (setq first-statement
2497                     (or
2498                      (looking-at idlwave-comment-line-start-skip)
2499                      (looking-at "[ \t]*$")
2500                      (looking-at (concat "[ \t]*" idlwave-label "[ \t]*$"))
2501                      (looking-at "^@")))
2502               (= (forward-line -1) 0)))
2503       ;; skip continuation lines
2504       (while (and
2505               (save-excursion
2506                 (forward-line -1)
2507                 (idlwave-is-continuation-line))
2508               (= (forward-line -1) 0)))
2509       first-statement)))
2510
2511 (defun idlwave-end-of-statement ()
2512   "Moves point to the end of the current IDL statement.
2513 If not in a statement just moves to end of line.  Returns position."
2514   (interactive)
2515   (while (and (idlwave-is-continuation-line)
2516               (= (forward-line 1) 0))
2517     (while (and (idlwave-is-comment-or-empty-line)
2518                 (= (forward-line 1) 0))))
2519   (end-of-line)
2520   (point))
2521
2522 (defun idlwave-end-of-statement0 ()
2523   "Moves point to the end of the current IDL statement.
2524 If not in a statement just moves to end of line. Returns position."
2525   (interactive)
2526   (while (and (idlwave-is-continuation-line)
2527               (= (forward-line 1) 0)))
2528   (end-of-line)
2529   (point))
2530
2531 (defun idlwave-next-statement ()
2532   "Moves point to beginning of the next IDL statement.
2533  Returns t if that statement is the last
2534  non-comment IDL statement in the file, and nil otherwise."
2535   (interactive)
2536   (let (last-statement)
2537     (idlwave-end-of-statement)
2538     ;; skip blank lines, label lines, include lines and line comments
2539     (while (and (= (forward-line 1) 0)
2540                 ;; The current statement is the last statement until
2541                 ;; we reach a new statement.
2542                 (setq last-statement
2543                       (or
2544                        (looking-at idlwave-comment-line-start-skip)
2545                        (looking-at "[ \t]*$")
2546                        (looking-at (concat "[ \t]*" idlwave-label "[ \t]*$"))
2547                        (looking-at "^@")))))
2548     last-statement))
2549
2550 (defun idlwave-skip-multi-commands (&optional lim)
2551   "Skip past multiple commands on a line (with `&')."
2552   (let ((save-point (point)))
2553     (when (re-search-forward ".*&" lim t)
2554       (goto-char (match-end 0))
2555       (if (idlwave-in-quote) (goto-char save-point)))
2556     (point)))
2557
2558 (defun idlwave-skip-label-or-case ()
2559   "Skip label or case statement element.
2560 Returns position after label.
2561 If there is no label point is not moved and nil is returned."
2562   ;; Case expressions and labels are terminated by a colon.
2563   ;; So we find the first colon in the line and make sure
2564   ;; - no `?' is before it (might be a ? b : c)
2565   ;; - it is not in a comment
2566   ;; - not in a string constant
2567   ;; - not in parenthesis (like a[0:3])
2568   ;; - not followed by another ":" in explicit class, ala a->b::c
2569   ;; As many in this mode, this function is heuristic and not an exact
2570   ;; parser. 
2571   (let* ((start (point))
2572          (eos (save-excursion (idlwave-end-of-statement) (point)))
2573          (end (idlwave-find-key ":" 1 'nomark eos)))
2574     (if (and end
2575              (= (nth 0 (parse-partial-sexp start end)) 0)
2576              (not (string-match "\\?" (buffer-substring start end)))
2577              (not (string-match "^::" (buffer-substring end eos))))
2578         (progn
2579           (forward-char)
2580           (point))
2581       (goto-char start)
2582       nil)))
2583
2584 (defun idlwave-start-of-substatement (&optional pre)
2585   "Move to start of next IDL substatement after point.
2586 Uses the type of the current IDL statement to determine if the next
2587 statement is on a new line or is a subpart of the current statement.
2588 Returns point at start of substatement modulo whitespace.
2589 If optional argument is non-nil move to beginning of current
2590 substatement."
2591   (let ((orig (point))
2592         (eos (idlwave-end-of-statement))
2593         (ifnest 0)
2594         st nst last)
2595     (idlwave-beginning-of-statement)
2596     (idlwave-skip-label-or-case)
2597     (idlwave-skip-multi-commands orig)
2598     (setq last (point))
2599     ;; Continue looking for substatements until we are past orig
2600     (while (and (<= (point) orig) (not (eobp)))
2601       (setq last (point))
2602       (setq nst (nth 1 (cdr (setq st (car (idlwave-statement-type))))))
2603       (if (equal (car st) 'if) (setq ifnest (1+ ifnest)))
2604       (cond ((and nst
2605                   (idlwave-find-key nst 1 'nomark eos))
2606              (goto-char (match-end 0)))
2607             ((and (> ifnest 0) (idlwave-find-key "\\<else\\>" 1 'nomark eos))
2608              (setq ifnest (1- ifnest))
2609              (goto-char (match-end 0)))
2610             (t (setq ifnest 0)
2611                (idlwave-next-statement))))
2612     (if pre (goto-char last))
2613     ;; If a continuation line starts here, move to next line
2614     (if (looking-at "[ \t]*\\$\\([ \t]*\\(;\\|$\\)\\)")
2615         (beginning-of-line 2))
2616     (point)))
2617
2618 (defun idlwave-statement-type ()
2619   "Return the type of the current IDL statement.
2620 Uses `idlwave-statement-match' to return a cons of (type . point) with
2621 point the ending position where the type was determined. Type is the
2622 association from `idlwave-statement-match', i.e. the cons cell from the
2623 list not just the type symbol. Returns nil if not an identifiable
2624 statement."
2625   (save-excursion
2626     ;; Skip whitespace within a statement which is spaces, tabs, continuations
2627     ;; and possibly comments
2628     (while (looking-at "[ \t]*\\$")
2629       (forward-line 1))
2630     (skip-chars-forward " \t")
2631     (let ((st idlwave-statement-match)
2632           (case-fold-search t))
2633       (while (and (not (looking-at (nth 0 (cdr (car st)))))
2634                   (setq st (cdr st))))
2635       (if st
2636           (append st (match-end 0))))))
2637
2638 (defun idlwave-expand-equal (&optional before after)
2639   "Pad '=' with spaces.
2640 Two cases: Assignment statement, and keyword assignment.
2641 The case is determined using `idlwave-start-of-substatement' and
2642 `idlwave-statement-type'.
2643 The equal sign will be surrounded by BEFORE and AFTER blanks.
2644 If `idlwave-pad-keyword' is t then keyword assignment is treated just
2645 like assignment statements.  When nil, spaces are removed for keyword
2646 assignment.  Any other value keeps the current space around the `='.
2647 Limits in for loops are treated as keyword assignment.
2648 See `idlwave-surround'. "
2649   ;; Even though idlwave-surround checks `idlwave-surround-by-blank' this
2650   ;; check saves the time of finding the statement type.
2651   (if idlwave-surround-by-blank
2652       (if (eq t idlwave-pad-keyword)  
2653           ;; Everything gets padded equally
2654           (idlwave-surround before after)
2655         ;; Treating keywords/for variables specially...
2656         (let ((st (save-excursion   ; To catch for variables
2657                     (idlwave-start-of-substatement t)
2658                     (idlwave-statement-type)))
2659               (what (save-excursion ; To catch keywords
2660                       (skip-chars-backward "= \t")
2661                       (nth 2 (idlwave-where)))))
2662           (cond ((or (memq what '(function-keyword procedure-keyword))
2663                      (eq st 'for)) 
2664                  (cond 
2665                   ((null idlwave-pad-keyword)
2666                    (idlwave-surround 0 0)) ; removed space
2667                   (t))) ; leave alone
2668                 (t (idlwave-surround before after)))))))
2669               
2670
2671 (defun idlwave-indent-and-action (&optional arg)
2672   "Call `idlwave-indent-line' and do expand actions.
2673 With prefix ARG non-nil, indent the entire sub-statement."
2674   (interactive "p")
2675   (save-excursion
2676     (if (and idlwave-expand-generic-end 
2677              (re-search-backward "\\<\\(end\\)\\s-*\\=" 
2678                                  (max 0 (- (point) 10)) t)
2679              (looking-at "\\(end\\)\\([ \n\t]\\|\\'\\)"))
2680         (progn (goto-char (match-end 1))
2681                ;;Expand the END abbreviation, just as RET or Space would have.
2682                (if abbrev-mode (expand-abbrev)
2683                  (idlwave-show-begin)))))
2684   (when (and (not arg) current-prefix-arg)
2685     (setq arg current-prefix-arg)
2686     (setq current-prefix-arg nil))
2687   (if arg 
2688       (idlwave-indent-statement)
2689     (idlwave-indent-line t)))
2690
2691 (defun idlwave-indent-line (&optional expand)
2692   "Indents current IDL line as code or as a comment.
2693 The actions in `idlwave-indent-action-table' are performed.
2694 If the optional argument EXPAND is non-nil then the actions in
2695 `idlwave-indent-expand-table' are performed."
2696   (interactive)
2697   ;; Move point out of left margin.
2698   (if (save-excursion
2699         (skip-chars-backward " \t")
2700         (bolp))
2701       (skip-chars-forward " \t"))
2702   (let ((mloc (point-marker)))
2703     (save-excursion
2704       (beginning-of-line)
2705       (if (looking-at idlwave-comment-line-start-skip)
2706           ;; Indentation for a line comment
2707           (progn
2708             (skip-chars-forward " \t")
2709             (idlwave-indent-left-margin (idlwave-comment-hook)))
2710         ;;
2711         ;; Code Line
2712         ;;
2713         ;; Before indenting, run action routines.
2714         ;;
2715         (if (and expand idlwave-do-actions)
2716             (mapcar 'idlwave-do-action idlwave-indent-expand-table))
2717         ;;
2718         (if idlwave-do-actions
2719             (mapcar 'idlwave-do-action idlwave-indent-action-table))
2720         ;;
2721         ;; No longer expand abbrevs on the line.  The user can do this
2722         ;; manually using expand-region-abbrevs.
2723         ;;
2724         ;; Indent for code line
2725         ;;
2726         (beginning-of-line)
2727         (if (or
2728              ;; a label line
2729              (looking-at (concat "^" idlwave-label "[ \t]*$"))
2730              ;; a batch command
2731              (looking-at "^[ \t]*@"))
2732             ;; leave flush left
2733             nil
2734           ;; indent the line
2735           (idlwave-indent-left-margin (idlwave-calculate-indent)))
2736         ;; Adjust parallel comment
2737         (end-of-line)
2738         (if (idlwave-in-comment)
2739             ;; Emacs 21 is too smart with fill-column on comment indent
2740             (let ((fill-column (if (fboundp 'comment-indent-new-line)
2741                                    (1- (frame-width))
2742                                  fill-column)))
2743               (indent-for-comment)))))
2744     (goto-char mloc)
2745     ;; Get rid of marker
2746     (set-marker mloc nil)))
2747
2748 (defun idlwave-do-action (action)
2749   "Perform an action repeatedly on a line.
2750 ACTION is a list (REG . FUNC).  REG is a regular expression.  FUNC is
2751 either a function name to be called with `funcall' or a list to be
2752 evaluated with `eval'.  The action performed by FUNC should leave point
2753 after the match for REG - otherwise an infinite loop may be entered."
2754   (let ((action-key (car action))
2755         (action-routine (cdr action)))
2756     (beginning-of-line)
2757     (while (idlwave-look-at action-key)
2758       (if (listp action-routine)
2759           (eval action-routine)
2760         (funcall action-routine)))))
2761
2762 (defun idlwave-indent-to (col &optional min)
2763   "Indent from point with spaces until column COL.
2764 Inserts space before markers at point."
2765   (if (not min) (setq min 0))
2766   (insert-before-markers
2767    (make-string (max min (- col (current-column))) ?\ )))
2768
2769 (defun idlwave-indent-left-margin (col)
2770   "Indent the current line to column COL.
2771 Indents such that first non-whitespace character is at column COL
2772 Inserts spaces before markers at point."
2773   (save-excursion
2774     (beginning-of-line)
2775     (delete-horizontal-space)
2776     (idlwave-indent-to col)))
2777
2778 (defun idlwave-indent-subprogram ()
2779   "Indents program unit which contains point."
2780   (interactive)
2781   (save-excursion
2782     (idlwave-end-of-statement)
2783     (idlwave-beginning-of-subprogram)
2784     (let ((beg (point)))
2785       (idlwave-forward-block)
2786       (message "Indenting subprogram...")
2787       (indent-region beg (point) nil))
2788     (message "Indenting subprogram...done.")))
2789
2790 (defun idlwave-indent-statement ()
2791   "Indent current statement, including all continuation lines."
2792   (interactive)
2793   (save-excursion
2794     (idlwave-beginning-of-statement)
2795     (let ((beg (point)))
2796       (idlwave-end-of-statement)
2797       (indent-region beg (point) nil))))
2798
2799 (defun idlwave-calculate-indent ()
2800   "Return appropriate indentation for current line as IDL code."
2801   (save-excursion
2802     (beginning-of-line)
2803     (cond
2804      ;; Check for beginning of unit - main (beginning of buffer), pro, or
2805      ;; function
2806      ((idlwave-look-at idlwave-begin-unit-reg)
2807       0)
2808      ;; Check for continuation line
2809      ((save-excursion
2810         (and (= (forward-line -1) 0)
2811              (idlwave-is-continuation-line)))
2812       (idlwave-calculate-cont-indent))
2813      ;; calculate indent based on previous and current statements
2814      (t (let ((the-indent
2815                ;; calculate indent based on previous statement
2816                (save-excursion
2817                  (cond
2818                   ((idlwave-previous-statement)
2819                    0)
2820                   ;; Main block
2821                   ((idlwave-look-at idlwave-begin-unit-reg t)
2822                    (+ (idlwave-current-statement-indent)
2823                       idlwave-main-block-indent))
2824                   ;; Begin block
2825                   ((idlwave-look-at idlwave-begin-block-reg t)
2826                    (+ (idlwave-current-statement-indent)
2827                       idlwave-block-indent))
2828                   ((idlwave-look-at idlwave-end-block-reg t)
2829                    (- (idlwave-current-statement-indent)
2830                       idlwave-end-offset
2831                       idlwave-block-indent))
2832                   ((idlwave-current-statement-indent))))))
2833           ;; adjust the indentation based on the current statement
2834           (cond
2835            ;; End block
2836            ((idlwave-look-at idlwave-end-block-reg)
2837             (+ the-indent idlwave-end-offset))
2838            (the-indent)))))))
2839
2840 ;;
2841 ;; Parentheses balacing/indent
2842 ;;
2843
2844 (defun idlwave-calculate-paren-indent (beg-reg end-reg close-exp)
2845   "Calculate the continuation indent inside a paren group.
2846 Returns a cons-cell with (open . indent), where open is the 
2847 location of the open paren"
2848   (let ((open (nth 1 (parse-partial-sexp beg-reg end-reg))))
2849     ;; Found an innermost open paren.
2850     (when open
2851       (goto-char open)
2852       ;; Line up with next word unless this is a closing paren.
2853       (cons open
2854             (cond
2855              ;; This is a closed paren - line up under open paren.
2856              (close-exp
2857               (current-column))
2858
2859              ;; Empty (or just comment) - just revert to basic indent
2860              ((progn
2861                 ;; Skip paren
2862                 (forward-char 1)
2863                 (looking-at "[ \t$]*\\(;.*\\)?$"))
2864               nil)
2865              
2866              ;; Line up with first word after any blank space
2867              ((progn
2868                 (skip-chars-forward " \t")
2869                 (current-column))))))))
2870
2871 (defun idlwave-calculate-cont-indent ()
2872   "Calculates the IDL continuation indent column from the previous statement.
2873 Note that here previous statement means the beginning of the current
2874 statement if this statement is a continuation of the previous line."
2875   (save-excursion
2876     (let* (open
2877            (case-fold-search t)
2878            (end-reg (progn (beginning-of-line) (point)))
2879            (close-exp (progn (skip-chars-forward " \t") (looking-at "\\s)")))
2880            (beg-last-statement (save-excursion (idlwave-previous-statement)
2881                                                (point)))
2882            (beg-reg (progn (idlwave-start-of-substatement 'pre) 
2883                            (if (eq (line-beginning-position) end-reg)
2884                                (goto-char beg-last-statement)
2885                              (point))))
2886            (cur-indent (idlwave-current-indent))
2887            (else-cont (and (goto-char end-reg) (looking-at "[ \t]*else")))
2888            (else-indent 
2889             (when else-cont
2890               (idlwave-find-key "\\<if\\>" -1 'nomark beg-last-statement)
2891               (current-column)))
2892            (basic-indent           ;; The basic, non-fancy indent
2893             (+ cur-indent idlwave-continuation-indent))
2894            (fancy-nonparen-indent  ;; A smarter indent for routine/assignments
2895             ;; Try without parens first:
2896             (progn
2897               (goto-char beg-reg)
2898               (while (idlwave-look-at "&"))  ; skip over continued statements
2899               (cond
2900                ;; A continued Procedure call or definition
2901                ((progn
2902                   (idlwave-look-at "^[ \t]*\\(pro\\|function\\)") ;skip over
2903                   (looking-at "[ \t]*\\([a-zA-Z0-9.$_]+[ \t]*->[ \t]*\\)?[a-zA-Z][:a-zA-Z0-9$_]*[ \t]*\\(,\\)[ \t]*"))
2904                 (goto-char (match-end 0))
2905                 ;; Comment only, or blank line with "$"?  Basic indent.
2906                 (if (save-match-data (looking-at "[ \t$]*\\(;.*\\)?$"))
2907                     nil
2908                   (current-column)))
2909
2910                ;; Continued assignment (with =):
2911                ((looking-at "[^=\n\r]*\\(=\\)[ \t]*")
2912                 (goto-char (match-end 0))
2913                 (if (looking-at (concat "[^\n\r]*" idlwave-block-match-regexp))
2914                     ;; block match? No longer in assignment....
2915                     ;;  a quoted block match doesn't count
2916                     (if (save-excursion
2917                           (goto-char (match-end 0))
2918                           (idlwave-in-quote)) 
2919                         (current-column))
2920                   (if (idlwave-in-quote) nil
2921                     ;; Comment only?  Revert to using basic indent
2922                     (if (save-match-data (looking-at "[ \t$]*\\(;.*\\)?$"))
2923                         nil
2924                       (current-column))))))))
2925            (fancy-nonparen-indent-allowed ;is it permitted?
2926             (and fancy-nonparen-indent
2927                  (< (- fancy-nonparen-indent basic-indent)
2928                     idlwave-max-extra-continuation-indent)))
2929            (fancy-paren-indent-cons     ;; A smarter indent for paren groups
2930             ;; Look for any enclosing parens
2931             (idlwave-calculate-paren-indent beg-reg end-reg close-exp))
2932            (fancy-paren-open (car fancy-paren-indent-cons))
2933            (fancy-paren-indent (cdr fancy-paren-indent-cons))
2934            (fancy-paren-indent-allowed   ; is it permitted
2935             (and fancy-paren-indent
2936                  (or idlwave-indent-to-open-paren ;; override
2937                      (< (- fancy-paren-indent basic-indent)
2938                         idlwave-max-extra-continuation-indent))))
2939             fancy-enclosing-paren-indent)
2940       (cond 
2941        ;; else continuations are always tied to their "if" line
2942        (else-cont 
2943         (or else-indent cur-indent))
2944
2945        ;; an allowed parenthesis-indent
2946        ((and fancy-paren-indent fancy-paren-indent-allowed)
2947         fancy-paren-indent)
2948
2949        ;; a disallowed paren indent nested inside one or more other
2950        ;; parens: indent relative to the first allowed enclosing paren
2951        ;; set, if any... if it's actually a larger indent, just use
2952        ;; the fancy-paren-indent anyway.
2953        ((and fancy-paren-indent
2954              (not fancy-paren-indent-allowed)
2955              (setq fancy-enclosing-paren-indent
2956                    (let ((enclose-open fancy-paren-open)
2957                          enclose-indent-cons
2958                          enclose-indent)
2959                      (catch 'loop
2960                        (while (setq enclose-indent-cons
2961                                     (idlwave-calculate-paren-indent 
2962                                      beg-reg (max (1- enclose-open) beg-reg)
2963                                      nil)
2964                                     enclose-open   (car enclose-indent-cons)
2965                                     enclose-indent (cdr enclose-indent-cons))
2966                          (if (< (- enclose-indent basic-indent)
2967                                 idlwave-max-extra-continuation-indent)
2968                              (throw 'loop enclose-indent)))))))
2969         (min fancy-paren-indent
2970              (+ fancy-enclosing-paren-indent idlwave-continuation-indent)))
2971                 
2972        ;; a disallowed paren indent inside another type: indent relative
2973        ((and fancy-paren-indent         
2974              (not fancy-paren-indent-allowed)
2975              fancy-nonparen-indent-allowed )
2976         (+ fancy-nonparen-indent idlwave-continuation-indent))
2977
2978        ;; an allowed nonparen-only indent
2979        ((and fancy-nonparen-indent fancy-nonparen-indent-allowed)
2980         fancy-nonparen-indent)
2981
2982        ;; everything else
2983        (t 
2984         basic-indent)))))
2985
2986 (defun idlwave-find-key (key-re &optional dir nomark limit)
2987   "Move to next match of the regular expression KEY-RE.
2988 Matches inside comments or string constants will be ignored.
2989 If DIR is negative, the search will be backwards.
2990 At a successful match, the mark is pushed unless NOMARK is non-nil.
2991 Searches are limited to LIMIT.
2992 Searches are case-insensitive and use a special syntax table which
2993 treats `$' and `_' as word characters.
2994 Return value is the beginning of the match or (in case of failure) nil."
2995   (setq dir (or dir 0))
2996   (let ((case-fold-search t)
2997         (search-func (if (> dir 0) 're-search-forward 're-search-backward))
2998         found)
2999     (idlwave-with-special-syntax
3000      (save-excursion
3001        (catch 'exit
3002          (while (funcall search-func key-re limit t)
3003            (if (not (idlwave-quoted))
3004                (throw 'exit (setq found (match-beginning 0)))
3005              (if (or (and (> dir 0) (eobp))
3006                      (and (< dir 0) (bobp)))
3007                  (throw 'exit nil)))))))
3008     (if found
3009         (progn
3010           (if (not nomark) (push-mark))
3011           (goto-char found)
3012           found)
3013       nil)))
3014
3015 (defun idlwave-block-jump-out (&optional dir nomark)
3016   "When optional argument DIR is non-negative, move forward to end of
3017 current block using the `idlwave-begin-block-reg' and `idlwave-end-block-reg'
3018 regular expressions. When DIR is negative, move backwards to block beginning.
3019 Recursively calls itself to skip over nested blocks. DIR defaults to
3020 forward. Calls `push-mark' unless the optional argument NOMARK is
3021 non-nil. Movement is limited by the start of program units because of
3022 possibility of unbalanced blocks."
3023   (interactive "P")
3024   (or dir (setq dir 0))
3025   (let* ((here (point))
3026          (case-fold-search t)
3027          (limit (if (>= dir 0) (point-max) (point-min)))
3028          (block-limit (if (>= dir 0) 
3029                           idlwave-begin-block-reg
3030                         idlwave-end-block-reg))
3031          found
3032          (block-reg (concat idlwave-begin-block-reg "\\|"
3033                             idlwave-end-block-reg))
3034          (unit-limit (or (save-excursion
3035                            (if (< dir 0)
3036                                (idlwave-find-key
3037                                 idlwave-begin-unit-reg dir t limit)
3038                              (end-of-line)
3039                              (idlwave-find-key 
3040                               idlwave-end-unit-reg dir t limit)))
3041                          limit)))
3042     (if (>= dir 0) (end-of-line)) ;Make sure we are in current block
3043     (if (setq found (idlwave-find-key  block-reg dir t unit-limit))
3044         (while (and found (looking-at block-limit))
3045           (if (>= dir 0) (forward-word 1))
3046           (idlwave-block-jump-out dir t)
3047           (setq found (idlwave-find-key block-reg dir t unit-limit))))
3048     (if (not nomark) (push-mark here))
3049     (if (not found) (goto-char unit-limit)
3050       (if (>= dir 0) (forward-word 1)))))
3051
3052 (defun idlwave-current-statement-indent ()
3053   "Return indentation of the current statement.
3054 If in a statement, moves to beginning of statement before finding indent."
3055   (idlwave-beginning-of-statement)
3056   (idlwave-current-indent))
3057
3058 (defun idlwave-current-indent ()
3059   "Return the column of the indentation of the current line.
3060 Skips any whitespace. Returns 0 if the end-of-line follows the whitespace."
3061   (save-excursion
3062     (beginning-of-line)
3063     (skip-chars-forward " \t")
3064     ;; if we are at the end of blank line return 0
3065     (cond ((eolp) 0)
3066           ((current-column)))))
3067
3068 (defun idlwave-is-continuation-line ()
3069   "Tests if current line is continuation line.
3070 Blank or comment-only lines following regular continuation lines (with
3071 `$') count as continuations too."
3072   (save-excursion
3073     (or 
3074      (idlwave-look-at "\\<\\$")
3075      (catch 'loop
3076        (while (and (looking-at "^[ \t]*\\(;.*\\)?$") 
3077                    (eq (forward-line -1) 0))
3078          (if (idlwave-look-at "\\<\\$") (throw 'loop t)))))))
3079
3080 (defun idlwave-is-comment-line ()
3081   "Tests if the current line is a comment line."
3082   (save-excursion
3083     (beginning-of-line 1)
3084     (looking-at "[ \t]*;")))
3085
3086 (defun idlwave-is-comment-or-empty-line ()
3087   "Tests if the current line is a comment line."
3088   (save-excursion
3089     (beginning-of-line 1)
3090     (looking-at "[ \t]*[;\n]")))
3091
3092 (defun idlwave-look-at (regexp &optional cont beg)
3093   "Searches current line from current point for REGEXP.
3094 If optional argument CONT is non-nil, searches to the end of
3095 the current statement.
3096 If optional arg BEG is non-nil, search starts from the beginning of the
3097 current statement.
3098 Ignores matches that end in a comment or inside a string expression.
3099 Returns point if successful, nil otherwise.
3100 This function produces unexpected results if REGEXP contains quotes or
3101 a comment delimiter. The search is case insensitive.
3102 If successful leaves point after the match, otherwise, does not move point."
3103   (let ((here (point))
3104         (case-fold-search t)
3105         (eos (save-excursion
3106                (if cont (idlwave-end-of-statement) (end-of-line))
3107                (point)))
3108         found)
3109     (idlwave-with-special-syntax
3110      (if beg (idlwave-beginning-of-statement))
3111      (while (and (setq found (re-search-forward regexp eos t))
3112                  (idlwave-quoted))))
3113     (if (not found) (goto-char here))
3114     found))
3115
3116 (defun idlwave-fill-paragraph (&optional nohang)
3117   "Fills paragraphs in comments.
3118 A paragraph is made up of all contiguous lines having the same comment
3119 leader (the leading whitespace before the comment delimiter and the
3120 comment delimiter).  In addition, paragraphs are separated by blank
3121 line comments. The indentation is given by the hanging indent of the
3122 first line, otherwise by the minimum indentation of the lines after
3123 the first line. The indentation of the first line does not change.
3124 Does not effect code lines. Does not fill comments on the same line
3125 with code.  The hanging indent is given by the end of the first match
3126 matching `idlwave-hang-indent-regexp' on the paragraph's first line . If the
3127 optional argument NOHANG is non-nil then the hanging indent is
3128 ignored."
3129   (interactive "P")
3130   ;; check if this is a line comment
3131   (if (save-excursion
3132         (beginning-of-line)
3133         (skip-chars-forward " \t")
3134         (looking-at comment-start))
3135       (let
3136           ((indent 999)
3137            pre here diff fill-prefix-reg bcl first-indent
3138            hang start end)
3139         ;; Change tabs to spaces in the surrounding paragraph.
3140         ;; The surrounding paragraph will be the largest containing block of
3141         ;; contiguous line comments. Thus, we may be changing tabs in
3142         ;; a much larger area than is needed, but this is the easiest
3143         ;; brute force way to do it.
3144         ;;
3145         ;; This has the undesirable side effect of replacing the tabs
3146         ;; permanently without the user's request or knowledge.
3147         (save-excursion
3148           (backward-paragraph)
3149           (setq start (point)))
3150         (save-excursion
3151           (forward-paragraph)
3152           (setq end (point)))
3153         (untabify start end)
3154         ;;
3155         (setq here (point))
3156         (beginning-of-line)
3157         (setq bcl (point))
3158         (re-search-forward
3159          (concat "^[ \t]*" comment-start "+")
3160          (save-excursion (end-of-line) (point))
3161          t)
3162         ;; Get the comment leader on the line and its length
3163         (setq pre (current-column))
3164         ;; the comment leader is the indentation plus exactly the
3165         ;; number of consecutive ";".
3166         (setq fill-prefix-reg
3167               (concat
3168                (setq fill-prefix
3169                      (regexp-quote
3170                       (buffer-substring (save-excursion
3171                                           (beginning-of-line) (point))
3172                                         (point))))
3173                "[^;]"))
3174         
3175         ;; Mark the beginning and end of the paragraph
3176         (goto-char bcl)
3177         (while (and (looking-at fill-prefix-reg)
3178                     (not (looking-at paragraph-separate))
3179                     (not (bobp)))
3180           (forward-line -1))
3181         ;; Move to first line of paragraph
3182         (if (/= (point) bcl)
3183             (forward-line 1))
3184         (setq start (point))
3185         (goto-char bcl)
3186         (while (and (looking-at fill-prefix-reg)
3187                     (not (looking-at paragraph-separate))
3188                     (not (eobp)))
3189           (forward-line 1))
3190         (beginning-of-line)
3191         (if (or (not (looking-at fill-prefix-reg))
3192                 (looking-at paragraph-separate))
3193             (forward-line -1))
3194         (end-of-line)
3195         ;; if at end of buffer add a newline (need this because
3196         ;; fill-region needs END to be at the beginning of line after
3197         ;; the paragraph or it will add a line).
3198         (if (eobp)
3199             (progn (insert ?\n) (backward-char 1)))
3200         ;; Set END to the beginning of line after the paragraph
3201         ;; END is calculated as distance from end of buffer
3202         (setq end (- (point-max) (point) 1))
3203         ;;
3204         ;; Calculate the indentation for the paragraph.
3205         ;;
3206         ;; In the following while statements, after one iteration
3207         ;; point will be at the beginning of a line in which case
3208         ;; the while will not be executed for the
3209         ;; the first paragraph line and thus will not affect the
3210         ;; indentation.
3211         ;;
3212         ;; First check to see if indentation is based on hanging indent.
3213         (if (and (not nohang) idlwave-hanging-indent
3214                  (setq hang
3215                        (save-excursion
3216                          (goto-char start)
3217                          (idlwave-calc-hanging-indent))))
3218             ;; Adjust lines of paragraph by inserting spaces so that
3219             ;; each line's indent is at least as great as the hanging
3220             ;; indent. This is needed for fill-paragraph to work with
3221             ;; a fill-prefix.
3222             (progn
3223               (setq indent hang)
3224               (beginning-of-line)
3225               (while (> (point) start)
3226                 (re-search-forward comment-start-skip
3227                                    (save-excursion (end-of-line) (point))
3228                                    t)
3229                 (if (> (setq diff (- indent (current-column))) 0)
3230                     (progn
3231                       (if (>= here (point))
3232                           ;; adjust the original location for the
3233                           ;; inserted text.
3234                           (setq here (+ here diff)))
3235                       (insert (make-string diff ?\ ))))
3236                 (forward-line -1))
3237               )
3238           
3239           ;; No hang. Instead find minimum indentation of paragraph
3240           ;; after first line.
3241           ;; For the following while statement, since START is at the
3242           ;; beginning of line and END is at the end of line
3243           ;; point is greater than START at least once (which would
3244           ;; be the case for a single line paragraph).
3245           (while (> (point) start)
3246             (beginning-of-line)
3247             (setq indent
3248                   (min indent
3249                        (progn
3250                          (re-search-forward
3251                           comment-start-skip
3252                           (save-excursion (end-of-line) (point))
3253                           t)
3254                          (current-column))))
3255             (forward-line -1))
3256           )
3257         (setq fill-prefix (concat fill-prefix
3258                                   (make-string (- indent pre)
3259                                                ?\ )))
3260         ;; first-line indent
3261         (setq first-indent
3262               (max
3263                (progn
3264                  (re-search-forward
3265                   comment-start-skip
3266                   (save-excursion (end-of-line) (point))
3267                   t)
3268                  (current-column))
3269                indent))
3270         
3271         ;; try to keep point at its original place
3272         (goto-char here)
3273
3274         ;; In place of the more modern fill-region-as-paragraph, a hack
3275         ;; to keep whitespace untouched on the first line within the
3276         ;; indent length and to preserve any indent on the first line
3277         ;; (first indent).
3278         (save-excursion
3279           (setq diff
3280                 (buffer-substring start (+ start first-indent -1)))
3281           (subst-char-in-region start (+ start first-indent -1) ?\  ?~ nil)
3282           (fill-region-as-paragraph
3283            start
3284            (- (point-max) end)
3285            (current-justification)
3286            nil)
3287           (delete-region start (+ start first-indent -1))
3288           (goto-char start)
3289           (insert diff))
3290         ;; When we want the point at the beginning of the comment
3291         ;; body fill-region will put it at the beginning of the line.
3292         (if (bolp) (skip-chars-forward (concat " \t" comment-start)))
3293         (setq fill-prefix nil))))
3294
3295 (defun idlwave-calc-hanging-indent ()
3296   "Calculate the position of the hanging indent for the comment
3297 paragraph.  The hanging indent position is given by the first match
3298 with the `idlwave-hang-indent-regexp'.  If `idlwave-use-last-hang-indent' is
3299 non-nil then use last occurrence matching `idlwave-hang-indent-regexp' on
3300 the line.
3301 If not found returns nil."
3302   (if idlwave-use-last-hang-indent
3303       (save-excursion
3304         (end-of-line)
3305         (if (re-search-backward
3306              idlwave-hang-indent-regexp
3307              (save-excursion (beginning-of-line) (point))
3308              t)
3309             (+ (current-column) (length idlwave-hang-indent-regexp))))
3310     (save-excursion
3311       (beginning-of-line)
3312       (if (re-search-forward
3313            idlwave-hang-indent-regexp
3314            (save-excursion (end-of-line) (point))
3315            t)
3316           (current-column)))))
3317
3318 (defun idlwave-auto-fill ()
3319   "Called to break lines in auto fill mode.
3320 Only fills comment lines if `idlwave-fill-comment-line-only' is non-nil.
3321 Places a continuation character at the end of the line
3322 if not in a comment.  Splits strings with IDL concatenation operator
3323 `+' if `idlwave-auto-fill-split-string is non-nil."
3324   (if (<= (current-column) fill-column)
3325       nil                             ; do not to fill
3326     (if (or (not idlwave-fill-comment-line-only)
3327             (save-excursion
3328               ;; Check for comment line
3329               (beginning-of-line)
3330               (looking-at idlwave-comment-line-start-skip)))
3331         (let (beg)
3332           (idlwave-indent-line)
3333           ;; Prevent actions do-auto-fill which calls indent-line-function.
3334           (let (idlwave-do-actions
3335                 (paragraph-start ".")
3336                 (paragraph-separate "."))
3337             (do-auto-fill))
3338           (save-excursion
3339             (end-of-line 0)
3340             ;; Indent the split line
3341             (idlwave-indent-line)
3342             )
3343           (if (save-excursion
3344                 (beginning-of-line)
3345                 (looking-at idlwave-comment-line-start-skip))
3346               ;; A continued line comment
3347               ;; We treat continued line comments as part of a comment
3348               ;; paragraph. So we check for a hanging indent.
3349               (if idlwave-hanging-indent
3350                   (let ((here (- (point-max) (point)))
3351                         (indent
3352                          (save-excursion
3353                            (forward-line -1)
3354                            (idlwave-calc-hanging-indent))))
3355                     (if indent
3356                         (progn
3357                           ;; Remove whitespace between comment delimiter and
3358                           ;; text, insert spaces for appropriate indentation.
3359                           (beginning-of-line)
3360                           (re-search-forward
3361                            comment-start-skip
3362                            (save-excursion (end-of-line) (point)) t)
3363                           (delete-horizontal-space)
3364                           (idlwave-indent-to indent)
3365                           (goto-char (- (point-max) here)))
3366                       )))
3367             ;; Split code or comment?
3368             (if (save-excursion
3369                   (end-of-line 0)
3370                   (idlwave-in-comment))
3371                 ;; Splitting a non-line comment.
3372                 ;; Insert the comment delimiter from split line
3373                 (progn
3374                   (save-excursion
3375                     (beginning-of-line)
3376                     (skip-chars-forward " \t")
3377                     ;; Insert blank to keep off beginning of line
3378                     (insert " "
3379                             (save-excursion
3380                               (forward-line -1)
3381                               (buffer-substring (idlwave-goto-comment)
3382                                                 (progn
3383                                                   (skip-chars-forward "; ")
3384                                                   (point))))))
3385                   (idlwave-indent-line))
3386               ;; Split code line - add continuation character
3387               (save-excursion
3388                 (end-of-line 0)
3389                 ;; Check to see if we split a string
3390                 (if (and (setq beg (idlwave-in-quote))
3391                          idlwave-auto-fill-split-string)
3392                     ;; Split the string and concatenate.
3393                     ;; The first extra space is for the space
3394                     ;; the line was split. That space was removed.
3395                     (insert " " (char-after beg) " +"))
3396                 (insert " $"))
3397               (if beg
3398                   (if idlwave-auto-fill-split-string
3399                       ;; Make the second part of continued string
3400                       (save-excursion
3401                         (beginning-of-line)
3402                         (skip-chars-forward " \t")
3403                         (insert (char-after beg)))
3404                     ;; Warning
3405                     (beep)
3406                     (message "Warning: continuation inside a string.")))
3407               ;; Although do-auto-fill (via indent-new-comment-line) calls
3408               ;; idlwave-indent-line for the new line, re-indent again
3409               ;; because of the addition of the continuation character.
3410               (idlwave-indent-line))
3411             )))))
3412
3413 (defun idlwave-auto-fill-mode (arg)
3414   "Toggle auto-fill mode for IDL mode.
3415 With arg, turn auto-fill mode on if arg is positive.
3416 In auto-fill mode, inserting a space at a column beyond `fill-column'
3417 automatically breaks the line at a previous space."
3418   (interactive "P")
3419   (prog1 (set idlwave-fill-function
3420               (if (if (null arg)
3421                       (not (symbol-value idlwave-fill-function))
3422                     (> (prefix-numeric-value arg) 0))
3423                   'idlwave-auto-fill
3424                 nil))
3425     ;; update mode-line
3426     (set-buffer-modified-p (buffer-modified-p))))
3427
3428 (defun idlwave-doc-header (&optional nomark )
3429   "Insert a documentation header at the beginning of the unit.
3430 Inserts the value of the variable idlwave-file-header. Sets mark before
3431 moving to do insertion unless the optional prefix argument NOMARK
3432 is non-nil."
3433   (interactive "P")
3434   (or nomark (push-mark))
3435   ;; make sure we catch the current line if it begins the unit
3436   (if idlwave-header-to-beginning-of-file
3437       (goto-char (point-min))
3438     (end-of-line)
3439     (idlwave-beginning-of-subprogram)
3440     (beginning-of-line)
3441     ;; skip function or procedure line
3442     (if (idlwave-look-at "\\<\\(pro\\|function\\)\\>")
3443         (progn
3444           (idlwave-end-of-statement)
3445           (if (> (forward-line 1) 0) (insert "\n")))))
3446   (let ((pos (point)))
3447     (if idlwave-file-header
3448         (cond ((car idlwave-file-header)
3449                (insert-file (car idlwave-file-header)))
3450               ((stringp (car (cdr idlwave-file-header)))
3451                (insert (car (cdr idlwave-file-header))))))
3452     (goto-char pos)))
3453
3454 (defun idlwave-default-insert-timestamp ()
3455   "Default timestamp insertion function"
3456   (insert (current-time-string))
3457   (insert ", " (user-full-name))
3458   (if (boundp 'user-mail-address)
3459       (insert " <" user-mail-address ">") 
3460     (insert " <" (user-login-name) "@" (system-name) ">"))
3461   ;; Remove extra spaces from line
3462   (idlwave-fill-paragraph)
3463   ;; Insert a blank line comment to separate from the date entry -
3464   ;; will keep the entry from flowing onto date line if re-filled.
3465   (insert "\n;\n;\t\t"))
3466
3467 (defun idlwave-doc-modification ()
3468   "Insert a brief modification log at the beginning of the current program.
3469 Looks for an occurrence of the value of user variable
3470 `idlwave-doc-modifications-keyword' if non-nil. Inserts time and user name
3471 and places the point for the user to add a log. Before moving, saves
3472 location on mark ring so that the user can return to previous point."
3473   (interactive)
3474   (push-mark)
3475   (let* (beg end)
3476     (if (and (or (re-search-backward idlwave-doclib-start nil t)
3477                  (progn
3478                    (goto-char (point-min))
3479                    (re-search-forward idlwave-doclib-start nil t)))
3480              (setq beg (match-beginning 0))
3481              (re-search-forward idlwave-doclib-end nil t)
3482              (setq end (match-end 0)))
3483         (progn
3484           (goto-char beg)
3485           (if (re-search-forward 
3486                (concat idlwave-doc-modifications-keyword ":")
3487                end t)
3488               (end-of-line)
3489             (goto-char end)
3490             (end-of-line -1)
3491             (insert "\n" comment-start "\n")
3492             (insert comment-start " " idlwave-doc-modifications-keyword ":"))
3493           (insert "\n;\n;\t")
3494           (run-hooks 'idlwave-timestamp-hook))
3495       (error "No valid DOCLIB header"))))
3496
3497 ;;; CJC 3/16/93
3498 ;;; Interface to expand-region-abbrevs which did not work when the
3499 ;;; abbrev hook associated with an abbrev moves point backwards
3500 ;;; after abbrev expansion, e.g., as with the abbrev '.n'.
3501 ;;; The original would enter an infinite loop in attempting to expand
3502 ;;; .n (it would continually expand and unexpand the abbrev without expanding
3503 ;;; because the point would keep going back to the beginning of the
3504 ;;; abbrev instead of to the end of the abbrev). We now keep the
3505 ;;; abbrev hook from moving backwards.
3506 ;;;
3507 (defun idlwave-expand-region-abbrevs (start end)
3508   "Expand each abbrev occurrence in the region.
3509 Calling from a program, arguments are START END."
3510   (interactive "r")
3511   (save-excursion
3512     (goto-char (min start end))
3513     (let ((idlwave-show-block nil)          ;Do not blink
3514           (idlwave-abbrev-move nil))        ;Do not move
3515       (expand-region-abbrevs start end 'noquery))))
3516
3517 (defun idlwave-quoted ()
3518   "Returns t if point is in a comment or quoted string.
3519 nil otherwise."
3520   (or (idlwave-in-comment) (idlwave-in-quote)))
3521
3522 (defun idlwave-in-quote ()
3523   "Returns location of the opening quote
3524 if point is in a IDL string constant, nil otherwise.
3525 Ignores comment delimiters on the current line.
3526 Properly handles nested quotation marks and octal
3527 constants - a double quote followed by an octal digit."
3528 ;;; Treat an octal inside an apostrophe to be a normal string. Treat a
3529 ;;; double quote followed by an octal digit to be an octal constant
3530 ;;; rather than a string. Therefore, there is no terminating double
3531 ;;; quote.
3532   (save-excursion
3533     ;; Because single and double quotes can quote each other we must
3534     ;; search for the string start from the beginning of line.
3535     (let* ((start (point))
3536            (eol (progn (end-of-line) (point)))
3537            (bq (progn (beginning-of-line) (point)))
3538            (endq (point))
3539            (data (match-data))
3540            delim
3541            found)
3542       (while  (< endq start)
3543         ;; Find string start
3544         ;; Don't find an octal constant beginning with a double quote
3545         (if (re-search-forward "\"[^0-7]\\|'\\|\"$" eol 'lim)
3546             ;; Find the string end.
3547             ;; In IDL, two consecutive delimiters after the start of a
3548             ;; string act as an
3549             ;; escape for the delimiter in the string.
3550             ;; Two consecutive delimiters alone (i.e., not after the
3551             ;; start of a string) is the null string.
3552             (progn
3553               ;; Move to position after quote
3554               (goto-char (1+ (match-beginning 0)))
3555               (setq bq (1- (point)))
3556               ;; Get the string delimiter
3557               (setq delim (char-to-string (preceding-char)))
3558               ;; Check for null string
3559               (if (looking-at delim)
3560                   (progn (setq endq (point)) (forward-char 1))
3561                 ;; Look for next unpaired delimiter
3562                 (setq found (search-forward delim eol 'lim))
3563                 (while (looking-at delim)
3564                   (forward-char 1)
3565                   (setq found (search-forward delim eol 'lim)))
3566                 (if found
3567                     (setq endq (- (point) 1))
3568                   (setq endq (point)))
3569                 ))
3570           (progn (setq bq (point)) (setq endq (point)))))
3571       (store-match-data data)
3572       ;; return string beginning position or nil
3573       (if (> start bq) bq))))
3574
3575 (defun idlwave-is-pointer-dereference (&optional limit)
3576   "Determines if the character after point is a pointer dereference *."
3577   (let ((pos (point)))
3578     (and
3579      (eq (char-after) ?\*)
3580      (not (idlwave-in-quote))
3581      (save-excursion
3582        (forward-char)
3583        (re-search-backward (concat "\\(" idlwave-idl-keywords 
3584                                    "\\|[[(*+-/=,^><]\\)\\s-*\\*") limit t)))))
3585
3586
3587 ;; Statement templates
3588
3589 ;; Replace these with a general template function, something like
3590 ;; expand.el (I think there was also something with a name similar to
3591 ;; dmacro.el)
3592
3593 (defun idlwave-template (s1 s2 &optional prompt noindent)
3594   "Build a template with optional prompt expression.
3595
3596 Opens a line if point is not followed by a newline modulo intervening
3597 whitespace.  S1 and S2 are strings.  S1 is inserted at point followed
3598 by S2.  Point is inserted between S1 and S2.  The case of S1 and S2 is
3599 adjusted according to `idlwave-abbrev-change-case'.  If optional argument
3600 PROMPT is a string then it is displayed as a message in the
3601 minibuffer.  The PROMPT serves as a reminder to the user of an
3602 expression to enter.
3603
3604 The lines containing S1 and S2 are reindented using `indent-region'
3605 unless the optional second argument NOINDENT is non-nil."
3606   (if (eq major-mode 'idlwave-shell-mode)
3607       ;; This is a gross hack to avoit template abbrev expansion
3608       ;; in the shell.  FIXME: This is a dirty hack.
3609       (if (and (eq this-command 'self-insert-command)
3610                (equal last-abbrev-location (point)))
3611           (insert last-abbrev-text)
3612         (error "No templates in idlwave-shell"))
3613     (cond ((eq idlwave-abbrev-change-case 'down)
3614            (setq s1 (downcase s1) s2 (downcase s2)))
3615           (idlwave-abbrev-change-case
3616            (setq s1 (upcase s1) s2 (upcase s2))))
3617     (let ((beg (save-excursion (beginning-of-line) (point)))
3618           end)
3619       (if (not (looking-at "\\s-*\n"))
3620           (open-line 1))
3621       (insert s1)
3622       (save-excursion
3623         (insert s2)
3624         (setq end (point)))
3625       (if (not noindent)
3626           (indent-region beg end nil))
3627       (if (stringp prompt)
3628           (message prompt)))))
3629   
3630 (defun idlwave-rw-case (string)
3631   "Make STRING have the case required by `idlwave-reserved-word-upcase'."
3632   (if idlwave-reserved-word-upcase
3633       (upcase string)
3634     string))
3635
3636 (defun idlwave-elif ()
3637   "Build skeleton IDL if-else block."
3638   (interactive)
3639   (idlwave-template
3640    (idlwave-rw-case "if")
3641    (idlwave-rw-case " then begin\n\nendif else begin\n\nendelse")
3642    "Condition expression"))
3643
3644 (defun idlwave-case ()
3645   "Build skeleton IDL case statement."
3646   (interactive)
3647   (idlwave-template 
3648    (idlwave-rw-case "case")
3649    (idlwave-rw-case " of\n\nendcase")
3650    "Selector expression"))
3651
3652 (defun idlwave-switch ()
3653   "Build skeleton IDL switch statement."
3654   (interactive)
3655   (idlwave-template 
3656    (idlwave-rw-case "switch")
3657    (idlwave-rw-case " of\n\nendswitch")
3658    "Selector expression"))
3659
3660 (defun idlwave-for ()
3661   "Build skeleton for loop statment."
3662   (interactive)
3663   (idlwave-template 
3664    (idlwave-rw-case "for")
3665    (idlwave-rw-case " do begin\n\nendfor")
3666    "Loop expression"))
3667
3668 (defun idlwave-if ()
3669   "Build skeleton for loop statment."
3670   (interactive)
3671   (idlwave-template
3672    (idlwave-rw-case "if")
3673    (idlwave-rw-case " then begin\n\nendif")
3674    "Scalar logical expression"))
3675
3676 (defun idlwave-procedure ()
3677   (interactive)
3678   (idlwave-template 
3679    (idlwave-rw-case "pro")
3680    (idlwave-rw-case "\n\nreturn\nend")
3681    "Procedure name"))
3682
3683 (defun idlwave-function ()
3684   (interactive)
3685   (idlwave-template 
3686    (idlwave-rw-case "function")
3687    (idlwave-rw-case "\n\nreturn\nend")
3688    "Function name"))
3689
3690 (defun idlwave-repeat ()
3691   (interactive)
3692   (idlwave-template
3693    (idlwave-rw-case "repeat begin\n\nendrep until")
3694    (idlwave-rw-case "")
3695    "Exit condition"))
3696
3697 (defun idlwave-while ()
3698   (interactive)
3699   (idlwave-template 
3700    (idlwave-rw-case "while")
3701    (idlwave-rw-case " do begin\n\nendwhile")
3702    "Entry condition"))
3703
3704 (defun idlwave-split-string (string &optional pattern)
3705   "Return a list of substrings of STRING which are separated by PATTERN.
3706 If PATTERN is omitted, it defaults to \"[ \\f\\t\\n\\r\\v]+\"."
3707   (or pattern
3708       (setq pattern "[ \f\t\n\r\v]+"))
3709   (let (parts (start 0))
3710     (while (string-match pattern string start)
3711       (setq parts (cons (substring string start (match-beginning 0)) parts)
3712             start (match-end 0)))
3713     (nreverse (cons (substring string start) parts))))
3714
3715 (defun idlwave-replace-string (string replace_string replace_with)
3716   (let* ((start 0)
3717          (last (length string))
3718          (ret_string "")
3719          end)
3720     (while (setq end (string-match replace_string string start))
3721       (setq ret_string
3722             (concat ret_string (substring string start end) replace_with))
3723       (setq start (match-end 0)))
3724     (setq ret_string (concat ret_string (substring string start last)))))
3725
3726 (defun idlwave-get-buffer-visiting (file)
3727   ;; Return the buffer currently visiting FILE
3728   (cond
3729    ((boundp 'find-file-compare-truenames) ; XEmacs
3730     (let ((find-file-compare-truenames t))
3731       (get-file-buffer file)))
3732    ((fboundp 'find-buffer-visiting)       ; Emacs
3733     (find-buffer-visiting file))
3734    (t (error "This should not happen (idlwave-get-buffer-visiting)"))))
3735
3736 (defvar idlwave-outlawed-buffers nil
3737   "List of buffer pulled up by idlwave for special reasons.
3738 Buffers in this list may be killed by `idlwave-kill-autoloaded-buffers'.")
3739
3740 (defun idlwave-find-file-noselect (file &optional why)
3741   ;; Return a buffer visiting file.
3742   (or (idlwave-get-buffer-visiting file)
3743       (let ((buf (find-file-noselect file)))
3744         (if why (add-to-list 'idlwave-outlawed-buffers (cons buf why)))
3745         buf)))
3746
3747 (defun idlwave-kill-autoloaded-buffers ()
3748   "Kill buffers created automatically by IDLWAVE.
3749 Function prompts for a letter to identify the buffers to kill.
3750 Possible letters are:
3751
3752 f    Buffers created by the command \\[idlwave-find-module] or mouse
3753      clicks in the routine info window.
3754 s    Buffers created by the IDLWAVE Shell to display where execution
3755      stopped or an error was found.
3756 a    Both of the above.
3757
3758 Buffer containing unsaved changes require confirmation before they are killed."
3759   (interactive)
3760   (if (null idlwave-outlawed-buffers)
3761       (error "No IDLWAVE-created buffers available")
3762     (princ (format "Kill IDLWAVE-created buffers: [f]ind source(%d), [s]hell display(%d), [a]ll ? "
3763                    (idlwave-count-outlawed-buffers 'find)
3764                    (idlwave-count-outlawed-buffers 'shell)))
3765     (let ((c (read-char)))
3766       (cond
3767        ((member c '(?f ?\C-f))
3768         (idlwave-do-kill-autoloaded-buffers 'find))
3769        ((member c '(?s ?\C-s))
3770         (idlwave-do-kill-autoloaded-buffers 'shell))
3771        ((member c '(?a ?\C-a))
3772         (idlwave-do-kill-autoloaded-buffers t))
3773        (t (error "Abort"))))))
3774
3775 (defun idlwave-count-outlawed-buffers (tag)
3776   "How many outlawed buffers have tag TAG?"
3777   (length (delq nil
3778                 (mapcar 
3779                  (lambda (x) (eq (cdr x) tag)) 
3780                  idlwave-outlawed-buffers))))
3781
3782 (defun idlwave-do-kill-autoloaded-buffers (&rest reasons)
3783   "Kill all buffers pulled up by IDLWAVE matching REASONS."
3784   (let* ((list (copy-sequence idlwave-outlawed-buffers))
3785          (cnt 0)
3786          entry)
3787     (while (setq entry (pop list))
3788       (if (buffer-live-p (car entry))
3789           (and (or (memq t reasons)
3790                    (memq (cdr entry) reasons))
3791                (kill-buffer (car entry))
3792                (incf cnt)
3793                (setq idlwave-outlawed-buffers 
3794                      (delq entry idlwave-outlawed-buffers)))
3795         (setq idlwave-outlawed-buffers 
3796               (delq entry idlwave-outlawed-buffers))))
3797     (message "%d buffer%s killed" cnt (if (= cnt 1) "" "s"))))
3798
3799 (defun idlwave-revoke-license-to-kill ()
3800   "Remove BUFFER from the buffers which may be killed.
3801 Killing would be done by `idlwave-do-kill-autoloaded-buffers'.
3802 Intended for `after-save-hook'."
3803   (let* ((buf (current-buffer))
3804          (entry (assq buf idlwave-outlawed-buffers)))
3805     ;; Revoke license
3806     (if entry
3807         (setq idlwave-outlawed-buffers 
3808               (delq entry idlwave-outlawed-buffers)))
3809     ;; Remove this function from the hook.
3810     (remove-hook 'after-save-hook 'idlwave-revoke-license-to-kill 'local)))
3811
3812 (defvar idlwave-path-alist)
3813 (defun idlwave-locate-lib-file (file)
3814   ;; Find FILE on the scanned lib path and return a buffer visiting it
3815   (let* ((dirs idlwave-path-alist)
3816          dir efile)
3817     (catch 'exit
3818       (while (setq dir (car (pop dirs)))
3819         (if (file-regular-p
3820              (setq efile (expand-file-name file dir)))
3821             (throw 'exit efile))))))
3822
3823 (defun idlwave-expand-lib-file-name (file)
3824   ;; Find FILE on the scanned lib path and return a buffer visiting it
3825   ;; This is for, e.g., finding source with no user catalog
3826   (cond 
3827    ((null file) nil)
3828    ((file-name-absolute-p file) file)
3829    (t (idlwave-locate-lib-file file))))
3830
3831 (defun idlwave-make-tags ()
3832   "Creates the IDL tags file IDLTAGS in the current directory from
3833 the list of directories specified in the minibuffer. Directories may be
3834 for example: . /usr/local/rsi/idl/lib. All the subdirectories of the
3835 specified top directories are searched if the directory name is prefixed
3836 by @. Specify @ directories with care, it may take a long, long time if
3837 you specify /."
3838   (interactive)
3839   (let (directory directories cmd append status numdirs dir getsubdirs
3840                   buffer save_buffer files numfiles item errbuf)
3841     
3842     ;;
3843     ;; Read list of directories
3844     (setq directory (read-string "Tag Directories: " "."))
3845     (setq directories (idlwave-split-string directory "[ \t]+"))
3846     ;;
3847     ;; Set etags command, vars
3848     (setq cmd "etags --output=IDLTAGS --language=none --regex='/[
3849 \\t]*[pP][Rr][Oo][ \\t]+\\([^ \\t,]+\\)/' --regex='/[
3850 \\t]*[Ff][Uu][Nn][Cc][Tt][Ii][Oo][Nn][ \\t]+\\([^ \\t,]+\\)/' ")
3851     (setq append " ")
3852     (setq status 0)
3853     ;;
3854     ;; For each directory
3855     (setq numdirs 0)
3856     (setq dir (nth numdirs directories))
3857     (while (and dir)
3858       ;;
3859       ;; Find the subdirectories
3860       (if (string-match "^[@]\\(.+\\)$" dir)
3861           (setq getsubdirs t) (setq getsubdirs nil))
3862       (if (and getsubdirs) (setq dir (substring dir 1 (length dir))))
3863       (setq dir (expand-file-name dir))
3864       (if (file-directory-p dir)
3865           (progn
3866             (if (and getsubdirs)
3867                 (progn
3868                   (setq buffer (get-buffer-create "*idltags*"))
3869                   (call-process "sh" nil buffer nil "-c"
3870                                 (concat "find " dir " -type d -print"))
3871                   (setq save_buffer (current-buffer))
3872                   (set-buffer buffer)
3873                   (setq files (idlwave-split-string
3874                                (idlwave-replace-string
3875                                 (buffer-substring 1 (point-max))
3876                                 "\n" "/*.pro ")
3877                                "[ \t]+"))
3878                   (set-buffer save_buffer)
3879                   (kill-buffer buffer))
3880               (setq files (list (concat dir "/*.pro"))))
3881             ;;
3882             ;; For each subdirectory
3883             (setq numfiles 0)
3884             (setq item (nth numfiles files))
3885             (while (and item)
3886               ;;
3887               ;; Call etags
3888               (if (not (string-match "^[ \\t]*$" item))
3889                   (progn
3890                     (message (concat "Tagging " item "..."))
3891                     (setq errbuf (get-buffer-create "*idltags-error*"))
3892                     (setq status (+ status
3893                                     (call-process "sh" nil errbuf nil "-c"
3894                                                   (concat cmd append item))))
3895                     ;;
3896                     ;; Append additional tags
3897                     (setq append " --append ")
3898                     (setq numfiles (1+ numfiles))
3899                     (setq item (nth numfiles files)))
3900                 (progn
3901                   (setq numfiles (1+ numfiles))
3902                   (setq item (nth numfiles files))
3903                   )))
3904             
3905             (setq numdirs (1+ numdirs))
3906             (setq dir (nth numdirs directories)))
3907         (progn
3908           (setq numdirs (1+ numdirs))
3909           (setq dir (nth numdirs directories)))))
3910     
3911     (setq errbuf (get-buffer-create "*idltags-error*"))
3912     (if (= status 0)
3913         (kill-buffer errbuf))
3914     (message "")
3915     ))
3916
3917 (defun idlwave-toggle-comment-region (beg end &optional n)
3918   "Comment the lines in the region if the first non-blank line is
3919 commented, and conversely, uncomment region. If optional prefix arg
3920 N is non-nil, then for N positive, add N comment delimiters or for N
3921 negative, remove N comment delimiters.
3922 Uses `comment-region' which does not place comment delimiters on
3923 blank lines."
3924   (interactive "r\nP")
3925   (if n
3926       (comment-region beg end (prefix-numeric-value n))
3927     (save-excursion
3928       (goto-char beg)
3929       (beginning-of-line)
3930       ;; skip blank lines
3931       (skip-chars-forward " \t\n")
3932       (if (looking-at (concat "[ \t]*\\(" comment-start "+\\)"))
3933           (if (fboundp 'uncomment-region)
3934               (uncomment-region beg end)
3935             (comment-region beg end
3936                             (- (length (buffer-substring
3937                                         (match-beginning 1)
3938                                         (match-end 1))))))
3939         (comment-region beg end)))))
3940
3941
3942 ;; ----------------------------------------------------------------------------
3943 ;; ----------------------------------------------------------------------------
3944 ;; ----------------------------------------------------------------------------
3945 ;; ----------------------------------------------------------------------------
3946 ;;
3947 ;; Completion and Routine Info
3948 ;;
3949
3950 ;; String "intern" functions
3951
3952 ;; For the completion and routine info function, we want to normalize
3953 ;; the case of procedure names etc.  We do this by "interning" these
3954 ;; string is a hand-crafted way.  Hashes are used to map the downcase
3955 ;; version of the strings to the cased versions.  Most *-sint-*
3956 ;; variables consist of *two* hashes, a buffer+shell, followed by a
3957 ;; system hash.  The former is re-scanned, and the latter takes case
3958 ;; precedence.
3959 ;;
3960 ;; Since these cased versions are really lisp objects, we can use `eq'
3961 ;; to search, which is a large performance boost.  All new strings
3962 ;; need to be "sinterned".  We do this as early as possible after
3963 ;; getting these strings from completion or buffer substrings.  So
3964 ;; most of the code can simply assume to deal with "sinterned"
3965 ;; strings.  The only exception is that the functions which scan whole
3966 ;; buffers for routine information do not intern the grabbed strings.
3967 ;; This is only done afterwards.  Therefore in these functions it is
3968 ;; *not* safe to assume the strings can be compared with `eq' and be
3969 ;; fed into the routine assq functions.
3970
3971 ;; Here we define the hashing functions.
3972
3973 ;; The variables which hold the hashes.
3974 (defvar idlwave-sint-routines '(nil))
3975 (defvar idlwave-sint-keywords '(nil))
3976 (defvar idlwave-sint-methods  '(nil))
3977 (defvar idlwave-sint-classes  '(nil))
3978 (defvar idlwave-sint-dirs    '(nil))
3979 (defvar idlwave-sint-libnames '(nil))
3980
3981 (defun idlwave-reset-sintern (&optional what)
3982   "Reset all sintern hashes."
3983   ;; Make sure the hash functions are accessible.
3984   (if (or (not (fboundp 'gethash))
3985           (not (fboundp 'puthash)))
3986       (progn 
3987         (require 'cl)
3988         (or (fboundp 'puthash)
3989             (defalias 'puthash 'cl-puthash))))
3990   (let ((entries '((idlwave-sint-routines 1000 10)
3991                    (idlwave-sint-keywords 1000 10)
3992                    (idlwave-sint-methods   100 10)
3993                    (idlwave-sint-classes    10 10))))
3994
3995     ;; Make sure these are lists
3996     (loop for entry in entries
3997       for var = (car entry)
3998       do (if (not (consp (symbol-value var))) (set var (list nil))))
3999
4000     (when (or (eq what t) (eq what 'syslib)
4001               (null (cdr idlwave-sint-routines)))
4002       ;; Reset the system & library hash
4003       (loop for entry in entries
4004         for var = (car entry) for size = (nth 1 entry)
4005         do (setcdr (symbol-value var) 
4006                    (make-hash-table ':size size ':test 'equal)))
4007       (setq idlwave-sint-dirs nil
4008             idlwave-sint-libnames nil))
4009
4010     (when (or (eq what t) (eq what 'bufsh)
4011               (null (car idlwave-sint-routines)))
4012       ;; Reset the buffer & shell hash
4013       (loop for entry in entries
4014         for var = (car entry) for size = (nth 1 entry)
4015         do (setcar (symbol-value var) 
4016                    (make-hash-table ':size size ':test 'equal))))))
4017
4018 (defun idlwave-sintern-routine-or-method (name &optional class set)
4019   (if class
4020       (idlwave-sintern-method name set)
4021     (idlwave-sintern-routine name set)))
4022
4023 (defun idlwave-sintern (stype &rest args)
4024   (apply (intern (concat "idlwave-sintern-" (symbol-name stype))) args))
4025
4026 ;;(defmacro idlwave-sintern (type var)
4027 ;;  `(cond ((not (stringp name)) name)
4028 ;;       ((gethash (downcase name) (cdr ,var)))
4029 ;;       ((gethash (downcase name) (car ,var)))
4030 ;;       (set (idlwave-sintern-set name ,type ,var set))
4031 ;;       (name)))
4032
4033 (defun idlwave-sintern-routine (name &optional set)
4034   (cond ((not (stringp name)) name)
4035         ((gethash (downcase name) (cdr idlwave-sint-routines)))
4036         ((gethash (downcase name) (car idlwave-sint-routines)))
4037         (set (idlwave-sintern-set name 'routine idlwave-sint-routines set))
4038         (name)))
4039 (defun idlwave-sintern-keyword (name &optional set)
4040   (cond ((not (stringp name)) name)
4041         ((gethash (downcase name) (cdr idlwave-sint-keywords)))
4042         ((gethash (downcase name) (car idlwave-sint-keywords)))
4043         (set (idlwave-sintern-set name 'keyword idlwave-sint-keywords set))
4044         (name)))
4045 (defun idlwave-sintern-method (name &optional set)
4046   (cond ((not (stringp name)) name)
4047         ((gethash (downcase name) (cdr idlwave-sint-methods)))
4048         ((gethash (downcase name) (car idlwave-sint-methods)))
4049         (set (idlwave-sintern-set name 'method idlwave-sint-methods set))
4050         (name)))
4051 (defun idlwave-sintern-class (name &optional set)
4052   (cond ((not (stringp name)) name)
4053         ((gethash (downcase name) (cdr idlwave-sint-classes)))
4054         ((gethash (downcase name) (car idlwave-sint-classes)))
4055         (set (idlwave-sintern-set name 'class idlwave-sint-classes set))
4056         (name)))
4057
4058 (defun idlwave-sintern-dir (dir &optional set)
4059   (car (or (member dir idlwave-sint-dirs)
4060            (setq idlwave-sint-dirs (cons dir idlwave-sint-dirs)))))
4061 (defun idlwave-sintern-libname (name &optional set)
4062   (car (or (member name idlwave-sint-libnames)
4063            (setq idlwave-sint-libnames (cons name idlwave-sint-libnames)))))
4064
4065 (defun idlwave-sintern-set (name type tables set)
4066   (let* ((func (or (cdr (assq type idlwave-completion-case))
4067                    'identity))
4068          (iname (funcall (if (eq func 'preserve) 'identity func) name))
4069          (table (if (eq set 'sys) (cdr tables) (car tables))))
4070     (puthash (downcase name) iname table)
4071     iname))
4072
4073 (defun idlwave-sintern-keyword-list (kwd-list &optional set)
4074   "Sintern a set of keywords (file (key . link) (key2 . link2) ...)"
4075   (mapcar (lambda(x)
4076             (setcar x (idlwave-sintern-keyword (car x) set)))
4077           (cdr kwd-list))
4078   kwd-list)
4079
4080 (defun idlwave-sintern-rinfo-list (list &optional set default-dir)
4081   "Sintern all strings in the rinfo LIST.  With optional parameter
4082 SET: also set new patterns.  Probably this will always have to be t.
4083 If DEFAULT-DIR is passed, it is used as the base of the directory"
4084   (let (entry name type class kwds res source call new)
4085     (while list
4086       (setq entry (car list)
4087             list (cdr list)
4088             name (car entry)
4089             type (nth 1 entry)
4090             class (nth 2 entry)
4091             source (nth 3 entry)
4092             call (nth 4 entry)
4093             kwds (nthcdr 5 entry))
4094
4095       ;; The class and name
4096       (if class
4097           (progn
4098             (if (symbolp class) (setq class (symbol-name class)))
4099             (setq class (idlwave-sintern-class class set))
4100             (setq name (idlwave-sintern-method name set)))
4101         (setq name (idlwave-sintern-routine name set)))
4102       
4103       ;; The source
4104       (let ((source-type (car source))
4105             (source-file  (nth 1 source))
4106             (source-dir  (if default-dir  
4107                              (file-name-as-directory default-dir)
4108                            (nth 2 source)))
4109             (source-lib (nth 3 source)))
4110         (if (stringp source-dir)
4111             (setq source-dir (idlwave-sintern-dir source-dir set)))
4112         (if (stringp source-lib)
4113             (setq source-lib (idlwave-sintern-libname source-lib set)))
4114         (setq source (list source-type source-file source-dir source-lib)))
4115       
4116       ;; The keywords
4117       (setq kwds (mapcar (lambda (x)
4118                            (idlwave-sintern-keyword-list x set))
4119                          kwds))
4120
4121       ;; Build a canonicalized list
4122       (setq new (nconc (list name type class source call) kwds)
4123             res (cons new res)))
4124     (nreverse res)))
4125
4126 ;; Creating new sintern tables
4127
4128 (defun idlwave-new-sintern-type (tag)
4129   "Define a variable and a function to sintern the new type TAG.
4130 This defines the function `idlwave-sintern-TAG' and the variable
4131 `idlwave-sint-TAGs'."
4132   (let* ((name (symbol-name tag))
4133          (names (concat name "s"))
4134          (var (intern (concat "idlwave-sint-" names)))
4135          (func (intern (concat "idlwave-sintern-" name))))
4136     (set var nil) ; initial value of the association list
4137     (fset func    ; set the function
4138           `(lambda (name &optional set)
4139              (cond ((not (stringp name)) name)
4140                    ((cdr (assoc (downcase name) ,var)))
4141                    (set
4142                     (setq ,var (cons (cons (downcase name) name) ,var))
4143                     name)
4144                    (name))))))
4145
4146 (defun idlwave-reset-sintern-type (tag)
4147   "Reset the sintern variable associated with TAG."
4148   (set (intern (concat "idlwave-sint-" (symbol-name tag) "s")) nil))
4149
4150 ;;---------------------------------------------------------------------------
4151
4152
4153 ;; The variables which hold the information
4154 (defvar idlwave-system-routines nil
4155   "Holds the routine-info obtained by scanning buffers.")
4156 (defvar idlwave-buffer-routines nil
4157   "Holds the routine-info obtained by scanning buffers.")
4158 (defvar idlwave-compiled-routines nil
4159   "Holds the routine-info obtained by asking the shell.")
4160 (defvar idlwave-unresolved-routines nil
4161   "Holds the unresolved routine-info obtained by asking the shell.")
4162 (defvar idlwave-user-catalog-routines nil
4163   "Holds the procedure routine-info from the user scan.")
4164 (defvar idlwave-library-catalog-routines nil
4165   "Holds the procedure routine-info from the library catalog files.")
4166 (defvar idlwave-path-alist nil
4167   "Alist with !PATH directories and zero or more flags if the dir has
4168 been scanned in a user catalog ('user) or discovered in a library
4169 catalog \('lib).")
4170 (defvar idlwave-true-path-alist nil
4171   "Like `idlwave-path-alist', but with true filenames.")
4172 (defvar idlwave-routines nil
4173   "Holds the combinded procedure/function/method routine-info.")
4174 (defvar idlwave-class-alist nil
4175   "Holds the class names known to IDLWAVE.")
4176 (defvar idlwave-class-history nil
4177   "The history of classes selected with the minibuffer.")
4178 (defvar idlwave-force-class-query nil)
4179 (defvar idlwave-before-completion-wconf nil
4180   "The window configuration just before the completion buffer was displayed.")
4181 (defvar idlwave-last-system-routine-info-cons-cell nil
4182   "The last cons cell in the system routine info.")
4183
4184 ;;
4185 ;; The code to get routine info from different sources.
4186
4187 (defvar idlwave-system-routines)
4188 (defvar idlwave-catalog-process nil
4189   "The background process currently updating the catalog.")
4190
4191 (defun idlwave-routines ()
4192   "Provide a list of IDL routines.
4193 This routine loads the builtin routines on the first call.  Later it
4194 only returns the value of the variable."
4195   (if (and idlwave-catalog-process
4196            (processp idlwave-catalog-process))
4197       (progn
4198         (cond
4199          ((equal (process-status idlwave-catalog-process) 'exit)
4200           (message "updating........")
4201           (setq idlwave-catalog-process nil)
4202           (idlwave-update-routine-info '(4)))
4203          ((equal (process-status idlwave-catalog-process) 'run)
4204           ;; Keep it running...
4205           )
4206          (t
4207           ;; Something is wrong, get rid of the process
4208           (message "Problem with catalog process") (beep)
4209           (condition-case nil
4210               (kill-process idlwave-catalog-process)
4211             (error nil))
4212           (setq idlwave-catalog-process nil)))))
4213   (or idlwave-routines
4214       (progn
4215         (idlwave-update-routine-info)
4216         ;; return the current value
4217         idlwave-routines)))
4218
4219 (defvar idlwave-update-rinfo-hook nil
4220   "List of functions which should run after a global rinfo update.
4221 Does not run after automatic updates of buffer or the shell.")
4222
4223 (defun idlwave-rescan-catalog-directories ()
4224   "Rescan the previously selected directories. For batch processing."
4225   (idlwave-update-routine-info '(16)))
4226
4227 (defun idlwave-rescan-asynchronously ()
4228   "Dispatch another emacs instance to update the idlwave catalog.
4229 After the process finishes normally, the first access to routine info
4230 will re-read the catalog."
4231   (interactive)
4232   (if (processp idlwave-catalog-process)
4233       (if (eq (process-status idlwave-catalog-process) 'run)
4234           (if (yes-or-no-p "A catalog-updating process is running.  Kill it? ")
4235               (progn
4236                 (condition-case nil
4237                     (kill-process idlwave-catalog-process)
4238                   (error nil))
4239                 (error "Process killed, no new process started"))
4240             (error "Quit"))
4241         (condition-case nil
4242             (kill-process idlwave-catalog-process)
4243           (error nil))))
4244   (if (or (not idlwave-user-catalog-file)
4245           (not (stringp idlwave-user-catalog-file))
4246           (not (file-regular-p idlwave-user-catalog-file)))
4247       (error "No catalog has been produced yet"))
4248   (let* ((emacs (expand-file-name (invocation-name) (invocation-directory)))
4249          (args (list "-batch"
4250                      "-l" (expand-file-name "~/.emacs")
4251                      "-l" "idlwave"
4252                      "-f" "idlwave-rescan-catalog-directories"))
4253          (process (apply 'start-process "idlcat" 
4254                          nil emacs args)))
4255     (setq idlwave-catalog-process process)
4256     (set-process-sentinel 
4257      process
4258      (lambda (pro why)
4259        (when (string-match "finished" why)
4260          (setq idlwave-routines nil
4261                idlwave-system-routines nil
4262                idlwave-catalog-process nil)
4263          (or (idlwave-start-load-rinfo-timer)
4264              (idlwave-update-routine-info '(4))))))
4265     (message "Background job started to update catalog file")))
4266
4267
4268 ;; Format for all routine info user catalog, library catalogs, etc.:
4269 ;;
4270 ;; ("ROUTINE" type class
4271 ;;  (system) | (lib pro_file dir "LIBNAME") | (user pro_file dir "USERLIB") |
4272 ;;  (buffer pro_file dir) | (compiled pro_file dir)
4273 ;;   "calling_string" ("HELPFILE" (("KWD1" . link1) ...)))
4274 ;;
4275 ;; DIR will be supplied dynamically while loading library catalogs,
4276 ;; and is sinterned to save space, as is LIBNAME.  PRO_FILE can be a
4277 ;; complete filepath, in which case DIR is unnecessary.  HELPFILE can
4278 ;; be nil, as can LINK1, etc., if no HTML help is available.
4279
4280
4281 (defvar idlwave-load-rinfo-idle-timer)
4282 (defun idlwave-update-routine-info (&optional arg)
4283   "Update the internal routine-info lists.
4284 These lists are used by `idlwave-routine-info' (\\[idlwave-routine-info])
4285 and by `idlwave-complete' (\\[idlwave-complete]) to provide information
4286 about individual routines.
4287
4288 The information can come from 4 sources:
4289 1. IDL programs in the current editing session
4290 2. Compiled modules in an IDL shell running as Emacs subprocess
4291 3. A list which covers the IDL system routines.
4292 4. A list which covers the prescanned library files.
4293
4294 Scans all IDLWAVE-mode buffers of the current editing session (see
4295 `idlwave-scan-all-buffers-for-routine-info').
4296 When an IDL shell is running, this command also queries the IDL program
4297 for currently compiled routines.
4298
4299 With prefix ARG, also reload the system and library lists.
4300 With two prefix ARG's, also rescans the chosen user catalog tree.
4301 With three prefix args, dispatch asynchronous process to do the update."
4302   (interactive "P")
4303   ;; Stop any idle processing
4304   (if (or (and (fboundp 'itimerp)
4305                (itimerp idlwave-load-rinfo-idle-timer))
4306           (and (fboundp 'timerp)
4307                (timerp idlwave-load-rinfo-idle-timer)))
4308       (cancel-timer idlwave-load-rinfo-idle-timer))
4309   (cond
4310    ((equal arg '(64))
4311     ;; Start a background process which updates the catalog.
4312     (idlwave-rescan-asynchronously))
4313    ((equal arg '(16))
4314     ;; Update the user catalog now, and wait for them.
4315     (idlwave-create-user-catalog-file t))
4316    (t
4317     (let* ((load (or arg
4318                      idlwave-buffer-case-takes-precedence
4319                      (null idlwave-routines)))
4320            ;; The override-idle means, even if the idle timer has done some
4321            ;; preparing work, load and renormalize everything anyway.
4322            (override-idle (or arg idlwave-buffer-case-takes-precedence)))
4323       
4324       (setq idlwave-buffer-routines nil
4325             idlwave-compiled-routines nil
4326             idlwave-unresolved-routines nil)
4327       ;; Reset the appropriate hashes
4328       (if (get 'idlwave-reset-sintern 'done-by-idle)
4329           ;; reset was already done in idle time, so skip this step now once
4330           (put 'idlwave-reset-sintern 'done-by-idle nil)
4331         (idlwave-reset-sintern (cond (load t)
4332                                      ((null idlwave-system-routines) t)
4333                                      (t 'bufsh))))
4334       
4335       (if idlwave-buffer-case-takes-precedence
4336           ;; We can safely scan the buffer stuff first
4337           (progn
4338             (idlwave-update-buffer-routine-info)
4339             (and load (idlwave-load-system-rinfo override-idle)))
4340         ;; We first do the system info, and then the buffers
4341         (and load (idlwave-load-system-rinfo override-idle))
4342         (idlwave-update-buffer-routine-info))
4343
4344       ;; Let's see if there is a shell
4345       (let* ((shell-is-running (and (fboundp 'idlwave-shell-is-running)
4346                                     (idlwave-shell-is-running)))
4347              (ask-shell (and shell-is-running
4348                              idlwave-query-shell-for-routine-info)))
4349       
4350         ;; Load the library catalogs again, first re-scanning the path
4351         (when arg 
4352           (if shell-is-running
4353               (idlwave-shell-send-command idlwave-shell-path-query
4354                                           '(progn
4355                                              (idlwave-shell-get-path-info)
4356                                              (idlwave-scan-library-catalogs))
4357                                           'hide)
4358             (idlwave-scan-library-catalogs)))
4359
4360         (if (or (not ask-shell)
4361                 (not (interactive-p)))
4362             ;; 1. If we are not going to ask the shell, we need to do the
4363             ;;    concatenation now.
4364             ;; 2. When this function is called non-interactively, it
4365             ;;    means that someone needs routine info *now*.  The
4366             ;;    shell update causes the concatenation to be
4367             ;;    *delayed*, so not in time for the current command.
4368             ;;    Therefore, we do a concatenation now, even though
4369             ;;    the shell might do it again.
4370             (idlwave-concatenate-rinfo-lists nil 'run-hooks))
4371       
4372         (when ask-shell
4373           ;; Ask the shell about the routines it knows of.
4374           (message "Querying the shell")
4375           (idlwave-shell-update-routine-info nil t)))))))
4376
4377
4378 (defvar idlwave-load-rinfo-steps-done (make-vector 6 nil))
4379 (defvar idlwave-load-rinfo-idle-timer nil)
4380 (defun idlwave-start-load-rinfo-timer ()
4381   (if (or (and (fboundp 'itimerp)
4382                (itimerp idlwave-load-rinfo-idle-timer))
4383           (and (fboundp 'timerp)
4384                (timerp idlwave-load-rinfo-idle-timer)))
4385       (cancel-timer idlwave-load-rinfo-idle-timer))
4386   (setq idlwave-load-rinfo-steps-done (make-vector 6 nil))
4387   (setq idlwave-load-rinfo-idle-timer nil)
4388   (if (and idlwave-init-rinfo-when-idle-after
4389            (numberp idlwave-init-rinfo-when-idle-after)
4390            (not (equal 0 idlwave-init-rinfo-when-idle-after))
4391            (not idlwave-routines))
4392       (condition-case nil
4393           (progn
4394             (setq idlwave-load-rinfo-idle-timer
4395                   (run-with-idle-timer
4396                    idlwave-init-rinfo-when-idle-after
4397                    nil 'idlwave-load-rinfo-next-step)))
4398         (error nil))))
4399
4400 (defun idlwave-load-rinfo-next-step ()
4401   (let ((inhibit-quit t)
4402         (arr idlwave-load-rinfo-steps-done))
4403     (when (catch 'exit
4404           (when (not (aref arr 0))
4405             (message "Loading idlw-rinfo.el in idle time...")
4406             (load "idlw-rinfo" 'noerror 'nomessage)
4407             (message "Loading idlw-rinfo.el in idle time...done")
4408             (aset arr 0 t)
4409             (throw 'exit t))
4410           (when (not (aref arr 1))
4411             (message "Normalizing idlwave-system-routines in idle time...")
4412             (idlwave-reset-sintern t)
4413             (put 'idlwave-reset-sintern 'done-by-idle t)
4414             (setq idlwave-system-routines
4415                   (idlwave-sintern-rinfo-list idlwave-system-routines 'sys))
4416             (message "Normalizing idlwave-system-routines in idle time...done")
4417             (aset arr 1 t)
4418             (throw 'exit t))
4419           (when (not (aref arr 2))
4420             (when (and (stringp idlwave-user-catalog-file)
4421                        (file-regular-p idlwave-user-catalog-file))
4422               (message "Loading user catalog in idle time...")
4423               (condition-case nil
4424                   (load-file idlwave-user-catalog-file)
4425                 (error (throw 'exit nil)))
4426               ;; Check for the old style catalog and warn
4427               (if (and
4428                    (boundp 'idlwave-library-routines)
4429                    idlwave-library-routines)
4430                   (progn
4431                     (setq idlwave-library-routines nil)
4432                     (ding)
4433                     (message "Outdated user catalog: %s... recreate" 
4434                              idlwave-user-catalog-file))
4435                 (message "Loading user catalog in idle time...done"))
4436               (aset arr 2 t)
4437               (throw 'exit t)))
4438           (when (not (aref arr 3))
4439             (when idlwave-user-catalog-routines
4440               (message "Normalizing user catalog routines in idle time...")
4441               (setq idlwave-user-catalog-routines 
4442                     (idlwave-sintern-rinfo-list
4443                      idlwave-user-catalog-routines 'sys))
4444               (message 
4445                "Normalizing user catalog routines in idle time...done"))
4446             (aset arr 3 t)
4447             (throw 'exit t))
4448           (when (not (aref arr 4))
4449             (idlwave-scan-library-catalogs 
4450              "Loading and normalizing library catalogs in idle time...")
4451             (aset arr 4 t)
4452             (throw 'exit t))
4453           (when (not (aref arr 5))
4454             (message "Finishing initialization in idle time...")
4455             (idlwave-routines)
4456             (message "Finishing initialization in idle time...done")
4457             (throw 'exit nil)))
4458         ;; restart the timer
4459         (if (sit-for 1)
4460             (idlwave-load-rinfo-next-step)
4461           (setq idlwave-load-rinfo-idle-timer
4462                 (run-with-idle-timer
4463                  idlwave-init-rinfo-when-idle-after
4464                  nil 'idlwave-load-rinfo-next-step))))))
4465
4466 (defun idlwave-load-system-rinfo (&optional force)
4467   ;; Load and case-treat the system and catalog files.
4468   (when (or force (not (aref idlwave-load-rinfo-steps-done 0)))
4469     (load "idlw-rinfo" 'noerror 'nomessage))
4470   (when (or force (not (aref idlwave-load-rinfo-steps-done 1)))
4471     (message "Normalizing idlwave-system-routines...")
4472     (setq idlwave-system-routines
4473           (idlwave-sintern-rinfo-list idlwave-system-routines 'sys))
4474     (message "Normalizing idlwave-system-routines...done"))
4475   (setq idlwave-routines (copy-sequence idlwave-system-routines))
4476   (setq idlwave-last-system-routine-info-cons-cell
4477         (nthcdr (1- (length idlwave-routines)) idlwave-routines))
4478   (when (and (stringp idlwave-user-catalog-file)
4479              (file-regular-p idlwave-user-catalog-file))
4480     (condition-case nil
4481         (when (or force (not (aref idlwave-load-rinfo-steps-done 2)))
4482           (load-file idlwave-user-catalog-file))
4483       (error nil))
4484     (when (boundp 'idlwave-library-routines)
4485       (setq idlwave-library-routines nil)
4486       (error "Outdated user catalog: %s... recreate" idlwave-user-catalog-file))
4487     (setq idlwave-true-path-alist nil)
4488     (when (or force (not (aref idlwave-load-rinfo-steps-done 3)))
4489       (message "Normalizing user catalog routines...")
4490       (setq idlwave-user-catalog-routines 
4491             (idlwave-sintern-rinfo-list 
4492              idlwave-user-catalog-routines 'sys))
4493       (message "Normalizing user catalog routines...done")))
4494   (when (or force (not (aref idlwave-load-rinfo-steps-done 4)))
4495     (idlwave-scan-library-catalogs
4496      "Loading and normalizing library catalogs..."))
4497   (run-hooks 'idlwave-after-load-rinfo-hook))
4498
4499
4500 (defun idlwave-update-buffer-routine-info ()
4501   (let (res)
4502     (cond 
4503      ((eq idlwave-scan-all-buffers-for-routine-info t)
4504       ;; Scan all buffers, current buffer last
4505       (message "Scanning all buffers...")
4506       (setq res (idlwave-get-routine-info-from-buffers 
4507                  (reverse (buffer-list)))))
4508      ((null idlwave-scan-all-buffers-for-routine-info)
4509       ;; Don't scan any buffers
4510       (setq res nil))
4511      (t
4512       ;; Just scan this buffer
4513       (if (eq major-mode 'idlwave-mode)
4514           (progn
4515             (message "Scanning current buffer...")
4516             (setq res (idlwave-get-routine-info-from-buffers
4517                        (list (current-buffer))))))))
4518     ;; Put the result into the correct variable
4519     (setq idlwave-buffer-routines 
4520           (idlwave-sintern-rinfo-list res 'set))))
4521
4522 (defun idlwave-concatenate-rinfo-lists (&optional quiet run-hook)
4523   "Put the different sources for routine information together."
4524   ;; The sequence here is important because earlier definitions shadow 
4525   ;; later ones.  We assume that if things in the buffers are newer
4526   ;; then in the shell of the system, it is meant to be different.
4527
4528   (setcdr idlwave-last-system-routine-info-cons-cell
4529           (append idlwave-buffer-routines
4530                   idlwave-compiled-routines
4531                   idlwave-library-catalog-routines
4532                   idlwave-user-catalog-routines))
4533   (setq idlwave-class-alist nil)
4534
4535   ;; Give a message with information about the number of routines we have.
4536   (unless quiet
4537     (message 
4538      "Routines Found: buffer(%d) compiled(%d) library(%d) user(%d) system(%d)"
4539      (length idlwave-buffer-routines)
4540      (length idlwave-compiled-routines)
4541      (length idlwave-library-catalog-routines)
4542      (length idlwave-user-catalog-routines)
4543      (length idlwave-system-routines)))
4544   (if run-hook
4545       (run-hooks 'idlwave-update-rinfo-hook)))
4546
4547 (defun idlwave-class-alist ()
4548   "Return the class alist - make it if necessary."
4549   (or idlwave-class-alist
4550       (let (class)
4551         (loop for x in idlwave-routines do
4552           (when (and (setq class (nth 2 x))
4553                      (not (assq class idlwave-class-alist)))
4554             (push (list class) idlwave-class-alist)))
4555         idlwave-class-alist)))      
4556
4557 ;; Three functions for the hooks
4558 (defun idlwave-save-buffer-update ()
4559   (idlwave-update-current-buffer-info 'save-buffer))
4560 (defun idlwave-kill-buffer-update ()
4561   (idlwave-update-current-buffer-info 'kill-buffer))
4562 (defun idlwave-new-buffer-update ()
4563   (idlwave-update-current-buffer-info 'find-file))
4564
4565 (defun idlwave-update-current-buffer-info (why)
4566   "Update idlwave-routines for current buffer.  Can run from after-save-hook."
4567   (when (and (eq major-mode 'idlwave-mode)
4568              (or (eq t idlwave-auto-routine-info-updates)
4569                  (memq why idlwave-auto-routine-info-updates))
4570              idlwave-scan-all-buffers-for-routine-info
4571              idlwave-routines)
4572     (condition-case nil
4573         (let (routines)
4574           (idlwave-replace-buffer-routine-info
4575            (buffer-file-name)
4576            (if (eq why 'kill-buffer)
4577                nil
4578              (setq routines
4579                    (idlwave-sintern-rinfo-list
4580                     (idlwave-get-routine-info-from-buffers
4581                      (list (current-buffer))) 'set))))
4582           (idlwave-concatenate-rinfo-lists 'quiet)
4583           routines)
4584       (error nil))))
4585
4586 (defun idlwave-replace-buffer-routine-info (file new)
4587   "Cut the part from FILE out of `idlwave-buffer-routines' and add NEW."
4588   (let ((list idlwave-buffer-routines) 
4589         found)
4590     (while list
4591       ;; The following test uses eq to make sure it works correctly
4592       ;; when two buffers visit the same file.  Then the file names
4593       ;; will be equal, but not eq.
4594       (if (eq (idlwave-routine-source-file (nth 3 (car list))) file)
4595           (progn
4596             (setcar list nil)
4597             (setq found t))
4598         (if found
4599             ;; End of that section reached. Jump. 
4600             (setq list nil)))
4601       (setq list (cdr list)))
4602     (setq idlwave-buffer-routines
4603           (append new (delq nil idlwave-buffer-routines)))))
4604
4605 ;;----- Scanning buffers -------------------
4606
4607 (defun idlwave-get-routine-info-from-buffers (buffers)
4608   "Call `idlwave-get-buffer-routine-info' on idlwave-mode buffers in BUFFERS."
4609   (let (buf routine-lists res)
4610     (save-excursion
4611       (while (setq buf (pop buffers))
4612         (set-buffer buf)
4613         (if (and (eq major-mode 'idlwave-mode)
4614                  buffer-file-name)
4615             ;; yes, this buffer has the right mode.
4616             (progn (setq res (condition-case nil
4617                                  (idlwave-get-buffer-routine-info)
4618                                (error nil)))
4619                    (push res routine-lists)))))
4620     ;; Concatenate the individual lists and return the result
4621     (apply 'nconc routine-lists)))
4622
4623 (defun idlwave-get-buffer-routine-info ()
4624   "Scan the current buffer for routine info.  Return (PRO-LIST FUNC-LIST)."
4625   (let* ((case-fold-search t)
4626          routine-list string entry)
4627     (save-excursion
4628       (save-restriction
4629         (widen)
4630         (goto-char (point-min))
4631         (while (re-search-forward 
4632                 "^[ \t]*\\(pro\\|function\\)[ \t]" nil t)
4633           (setq string (buffer-substring-no-properties
4634                         (match-beginning 0)
4635                         (progn 
4636                           (idlwave-end-of-statement)
4637                           (point))))
4638           (setq entry (idlwave-parse-definition string))
4639           (push entry routine-list))))
4640     routine-list))
4641
4642 (defvar idlwave-scanning-lib-dir)
4643 (defun idlwave-parse-definition (string)
4644   "Parse a module definition."
4645   (let ((case-fold-search t)
4646         start name args type keywords class)
4647     ;; Remove comments
4648     (while (string-match ";.*" string)
4649       (setq string (replace-match "" t t string)))
4650     ;; Remove the continuation line stuff
4651     (while (string-match "\\([^a-zA-Z0-9$_]\\)\\$[ \t]*\n" string)
4652       (setq string (replace-match "\\1 " t nil string)))
4653     (while (string-match "\n" string)
4654       (setq string (replace-match " " t nil string)))
4655     ;; Match the name and type.
4656     (when (string-match
4657            "\\<\\(pro\\|function\\)\\>\\s-+\\(\\([a-zA-Z0-9$_]+\\)::\\)?\\([a-zA-Z0-9$_]+\\)" string)
4658       (setq start (match-end 0))
4659       (setq type (downcase (match-string 1 string)))
4660       (if (match-beginning 3)
4661           (setq class (match-string 3 string)))
4662       (setq name (match-string 4 string)))
4663     ;; Match normal args and keyword args
4664     (while (string-match
4665             ",\\s-*\\([a-zA-Z][a-zA-Z0-9$_]*\\|\\(_ref\\)?_extra\\)\\s-*\\(=\\)?"
4666             string start)
4667       (setq start (match-end 0))
4668       (if (match-beginning 3)
4669           (push (match-string 1 string) keywords)
4670         (push (match-string 1 string) args)))
4671     ;; Normalize and sort.
4672     (setq args (nreverse args))
4673     (setq keywords (sort keywords (lambda (a b) 
4674                                     (string< (downcase a) (downcase b)))))
4675     ;; Make and return the entry
4676     ;; We don't know which argument are optional, so this information
4677     ;; will not be contained in the calling sequence.
4678     (list name
4679           (if (equal type "pro") 'pro 'fun)
4680           class
4681           (cond ((not (boundp 'idlwave-scanning-lib))
4682                  (list  'buffer (buffer-file-name)))
4683 ;               ((string= (downcase 
4684 ;                          (file-name-sans-extension
4685 ;                           (file-name-nondirectory (buffer-file-name))))
4686 ;                         (downcase name))
4687 ;                (list 'lib))
4688 ;               (t (cons 'lib (file-name-nondirectory (buffer-file-name))))
4689                 (t (list 'user (file-name-nondirectory (buffer-file-name))
4690                          idlwave-scanning-lib-dir "UserLib")))
4691           (concat 
4692            (if (string= type "function") "Result = " "")
4693            (if class "Obj ->[%s::]" "")
4694            "%s"
4695            (if args
4696                (concat
4697                 (if (string= type "function") "(" ", ")
4698                 (mapconcat 'identity args ", ")
4699                 (if (string= type "function") ")" ""))))
4700           (if keywords
4701               (cons nil (mapcar 'list keywords)) ;No help file
4702             nil))))
4703
4704
4705 ;;----- Scanning the user catalog -------------------
4706
4707 (defun idlwave-sys-dir ()
4708   "Return the syslib directory, or a dummy that never matches."
4709   (if (string= idlwave-system-directory "")
4710       "@@@@@@@@"
4711     idlwave-system-directory))
4712
4713
4714 (defvar idlwave-shell-path-query)
4715 (defun idlwave-create-user-catalog-file (&optional arg)
4716   "Scan all files on selected dirs of IDL search path for routine information.
4717
4718 A widget checklist will allow you to choose the directories.  Write
4719 the result as a file `idlwave-user-catalog-file'.  When this file
4720 exists, will be automatically loaded to give routine information about
4721 library routines.  With ARG, just rescan the same directories as last
4722 time - so no widget will pop up."
4723   (interactive "P")
4724   ;; Make sure the file is loaded if it exists.
4725   (if (and (stringp idlwave-user-catalog-file)
4726            (file-regular-p idlwave-user-catalog-file))
4727       (condition-case nil
4728           (load-file idlwave-user-catalog-file)
4729         (error nil)))
4730   ;; Make sure the file name makes sense
4731   (unless (and (stringp idlwave-user-catalog-file)
4732                (> (length idlwave-user-catalog-file) 0)
4733                (file-accessible-directory-p
4734                 (file-name-directory idlwave-user-catalog-file))
4735                (not (string= "" (file-name-nondirectory 
4736                                  idlwave-user-catalog-file))))
4737     (error "`idlwave-user-catalog-file' does not point to a file in an accessible directory"))
4738   
4739   (cond
4740     ;; Rescan the known directories
4741    ((and arg idlwave-path-alist
4742          (consp (car idlwave-path-alist)))
4743     (idlwave-scan-user-lib-files idlwave-path-alist))
4744
4745    ;; Expand the directories from library-path and run the widget
4746    (idlwave-library-path
4747     (idlwave-display-user-catalog-widget
4748      (if idlwave-true-path-alist 
4749          ;; Propagate any flags on the existing path-alist
4750          (mapcar (lambda (x)
4751                    (let ((path-entry (assoc (file-truename x)
4752                                             idlwave-true-path-alist)))
4753                      (if path-entry
4754                          (cons x (cdr path-entry)) 
4755                        (list x))))
4756                  (idlwave-expand-path idlwave-library-path))
4757        (mapcar 'list (idlwave-expand-path idlwave-library-path)))))
4758
4759    ;; Ask the shell for the path and then run the widget
4760    (t
4761     (message "Asking the shell for IDL path...")
4762     (require 'idlw-shell)
4763     (idlwave-shell-send-command idlwave-shell-path-query
4764                                 '(idlwave-user-catalog-command-hook nil)
4765                                 'hide))))
4766
4767
4768 ;; Parse shell path information and select among it.
4769 (defun idlwave-user-catalog-command-hook (&optional arg)
4770   ;; Command hook used by `idlwave-create-user-catalog-file'.
4771   (if arg
4772       ;; Scan immediately
4773       (idlwave-scan-user-lib-files idlwave-path-alist)
4774     ;; Set the path and display the widget
4775     (idlwave-shell-get-path-info 'no-write) ; set to something path-alist
4776     (idlwave-scan-library-catalogs "Locating library catalogs..." 'no-load)
4777     (idlwave-display-user-catalog-widget idlwave-path-alist)))
4778
4779 (defconst idlwave-user-catalog-widget-help-string 
4780   "This is the front-end to the creation of the IDLWAVE user catalog.
4781 Please select the directories on IDL's search path from which you
4782 would like to extract routine information, to be stored in the file:
4783
4784              %s
4785
4786 If this is not the correct file, first set variable
4787 `idlwave-user-catalog-file', and call this command again.
4788
4789 N.B. Many libraries include pre-scanned catalog files
4790 \(\".idlwave_catalog\").  These are marked with \"[LIB]\", and need
4791 not be scanned.  You can scan your own libraries off-line using the
4792 perl script `idlwave_catalog'.
4793
4794 After selecting the directories, choose [Scan & Save] to scan the library
4795 directories and save the routine info.
4796 \n")
4797
4798 (defvar idlwave-widget)
4799 (defvar widget-keymap)
4800 (defun idlwave-display-user-catalog-widget (dirs-list)
4801   "Create the widget to select IDL search path directories for scanning."
4802   (interactive)
4803   (require 'widget)
4804   (require 'wid-edit)
4805   (unless dirs-list
4806       (error "Don't know IDL's search path"))
4807
4808   (kill-buffer (get-buffer-create "*IDLWAVE Widget*"))
4809   (switch-to-buffer (get-buffer-create "*IDLWAVE Widget*"))
4810   (kill-all-local-variables)
4811   (make-local-variable 'idlwave-widget)
4812   (widget-insert (format idlwave-user-catalog-widget-help-string
4813                          idlwave-user-catalog-file))
4814   
4815   (widget-create 'push-button
4816                  :notify 'idlwave-widget-scan-user-lib-files
4817                  "Scan & Save")
4818   (widget-insert "  ")
4819   (widget-create 'push-button
4820                  :notify 'idlwave-delete-user-catalog-file
4821                  "Delete File")
4822   (widget-insert "  ")
4823   (widget-create 'push-button
4824                  :notify 
4825                  '(lambda (&rest ignore)
4826                     (let ((path-list (widget-get idlwave-widget :path-dirs)))
4827                       (mapcar (lambda (x)
4828                                 (unless (memq 'lib (cdr x))
4829                                   (idlwave-path-alist-add-flag x 'user)))
4830                               path-list)
4831                       (idlwave-display-user-catalog-widget path-list)))
4832                  "Select All Non-Lib")
4833   (widget-insert "  ")
4834   (widget-create 'push-button
4835                  :notify 
4836                  '(lambda (&rest ignore)
4837                     (let ((path-list (widget-get idlwave-widget :path-dirs)))
4838                       (mapcar (lambda (x)
4839                                 (idlwave-path-alist-remove-flag x 'user))
4840                               path-list)
4841                       (idlwave-display-user-catalog-widget path-list)))
4842                  "Deselect All")
4843   (widget-insert "  ")
4844   (widget-create 'push-button
4845                  :notify (lambda (&rest ignore)
4846                            (kill-buffer (current-buffer)))
4847                  "Quit")
4848   (widget-insert "\n\n")
4849
4850   (widget-insert "Select Directories: \n")
4851   
4852   (setq idlwave-widget
4853         (apply 'widget-create
4854                'checklist
4855                :value  (delq nil (mapcar (lambda (x) 
4856                                            (if (memq 'user (cdr x)) 
4857                                                (car x)))
4858                                          dirs-list))
4859                :greedy t
4860                :tag "List of directories"
4861                (mapcar (lambda (x) 
4862                          (list 'item 
4863                                (if (memq 'lib (cdr x))
4864                                    (concat "[LIB] " (car x) )
4865                                  (car x)))) dirs-list)))
4866   (widget-put idlwave-widget :path-dirs dirs-list)
4867   (widget-insert "\n")
4868   (use-local-map widget-keymap)
4869   (widget-setup)
4870   (goto-char (point-min))
4871   (delete-other-windows))
4872   
4873 (defun idlwave-delete-user-catalog-file (&rest ignore)
4874   (if (yes-or-no-p
4875        (format "Delete file %s " idlwave-user-catalog-file))
4876       (progn
4877         (delete-file idlwave-user-catalog-file)
4878         (message "%s has been deleted" idlwave-user-catalog-file))))
4879
4880 (defun idlwave-widget-scan-user-lib-files (&rest ignore)
4881   ;; Call `idlwave-scan-user-lib-files' with data taken from the widget.
4882   (let* ((widget idlwave-widget)
4883          (selected-dirs (widget-value widget))
4884          (path-alist (widget-get widget :path-dirs))
4885          (this-path-alist path-alist)
4886          dir-entry)
4887     (while (setq dir-entry (pop this-path-alist))
4888       (if (member 
4889            (if (memq 'lib (cdr dir-entry))
4890                (concat "[LIB] " (car dir-entry))
4891              (car dir-entry))
4892            selected-dirs)
4893           (idlwave-path-alist-add-flag dir-entry 'user)
4894         (idlwave-path-alist-remove-flag dir-entry 'user)))
4895     (idlwave-scan-user-lib-files path-alist)))
4896
4897 (defvar font-lock-mode)
4898 (defun idlwave-scan-user-lib-files (path-alist)
4899   ;; Scan the PRO files in PATH-ALIST and store the info in the user catalog
4900   (let* ((idlwave-scanning-lib t)
4901          (idlwave-scanning-lib-dir "")
4902          (idlwave-completion-case nil)
4903          dirs-alist dir files file)
4904     (setq idlwave-user-catalog-routines nil
4905           idlwave-path-alist path-alist ; for library-path instead
4906           idlwave-true-path-alist nil)
4907     (if idlwave-auto-write-paths (idlwave-write-paths))
4908     (save-excursion
4909       (set-buffer (get-buffer-create "*idlwave-scan.pro*"))
4910       (idlwave-mode)
4911       (setq dirs-alist (reverse path-alist))
4912       (while (setq dir (pop dirs-alist))
4913         (when (memq 'user (cdr dir))    ; Has it marked for scan?
4914           (setq dir (car dir))
4915           (setq idlwave-scanning-lib-dir dir)
4916           (when (file-directory-p dir)
4917             (setq files (directory-files dir 'full "\\.[pP][rR][oO]\\'"))
4918             (while (setq file (pop files))
4919               (when (file-regular-p file)
4920                 (if (not (file-readable-p file))
4921                     (message "Skipping %s (no read permission)" file)
4922                   (message "Scanning %s..." file)
4923                   (erase-buffer)
4924                   (insert-file-contents file 'visit)
4925                   (setq idlwave-user-catalog-routines
4926                         (append (idlwave-get-routine-info-from-buffers
4927                                  (list (current-buffer)))
4928                                 idlwave-user-catalog-routines)))))))))
4929     (message "Creating user catalog file...")
4930     (kill-buffer "*idlwave-scan.pro*")
4931     (kill-buffer (get-buffer-create "*IDLWAVE Widget*"))
4932     (let ((font-lock-maximum-size 0)
4933           (auto-mode-alist nil))
4934       (find-file idlwave-user-catalog-file))
4935     (if (and (boundp 'font-lock-mode)
4936              font-lock-mode)
4937         (font-lock-mode 0))
4938     (erase-buffer)
4939     (insert ";; IDLWAVE user catalog file\n")
4940     (insert (format ";; Created %s\n\n" (current-time-string)))
4941
4942     ;; Define the routine info list
4943     (insert "\n(setq idlwave-user-catalog-routines\n    '(")
4944     (let ((standard-output (current-buffer)))
4945       (mapcar (lambda (x)
4946                 (insert "\n    ")
4947                 (prin1 x)
4948                 (goto-char (point-max)))
4949               idlwave-user-catalog-routines))
4950     (insert (format "))\n\n;;; %s ends here\n"
4951                     (file-name-nondirectory idlwave-user-catalog-file)))
4952     (goto-char (point-min))
4953     ;; Save the buffer
4954     (save-buffer 0)
4955     (kill-buffer (current-buffer)))
4956   (message "Creating user catalog file...done")
4957   (message "Info for %d routines saved in %s"
4958            (length idlwave-user-catalog-routines)
4959            idlwave-user-catalog-file)
4960   (sit-for 2)
4961   (idlwave-update-routine-info t))
4962
4963 (defun idlwave-read-paths ()
4964   (if (and (stringp idlwave-path-file)
4965            (file-regular-p idlwave-path-file))
4966       (condition-case nil
4967           (load idlwave-path-file t t t)
4968         (error nil))))
4969
4970 (defun idlwave-write-paths ()
4971   (interactive)
4972   (when (and idlwave-path-alist idlwave-system-directory)
4973     (let ((font-lock-maximum-size 0)
4974           (auto-mode-alist nil))
4975       (find-file idlwave-path-file))
4976     (if (and (boundp 'font-lock-mode)
4977              font-lock-mode)
4978         (font-lock-mode 0))
4979     (erase-buffer)
4980     (insert ";; IDLWAVE paths\n")
4981     (insert (format ";; Created %s\n\n" (current-time-string)))
4982     ;; Define the variable which knows the value of "!DIR"
4983     (insert (format "\n(setq idlwave-system-directory \"%s\")\n"
4984                     idlwave-system-directory))
4985   
4986     ;; Define the variable which contains a list of all scanned directories
4987     (insert "\n(setq idlwave-path-alist\n    '(")
4988     (let ((standard-output (current-buffer)))
4989       (mapcar (lambda (x)
4990                 (insert "\n      ")
4991                 (prin1 x)
4992                 (goto-char (point-max)))
4993               idlwave-path-alist))
4994     (insert "))\n")
4995     (save-buffer 0)
4996     (kill-buffer (current-buffer))))
4997
4998
4999 (defun idlwave-expand-path (path &optional default-dir)
5000   ;; Expand parts of path starting with '+' recursively into directory list.
5001   ;; Relative recursive path elements are expanded relative to DEFAULT-DIR.
5002   (message "Expanding path...")
5003   (let (path1 dir recursive)
5004     (while (setq dir (pop path))
5005       (if (setq recursive (string= (substring dir 0 1) "+"))
5006           (setq dir (substring dir 1)))
5007       (if (and recursive
5008                (not (file-name-absolute-p dir)))
5009           (setq dir (expand-file-name dir default-dir)))
5010       (if recursive
5011           ;; Expand recursively
5012           (setq path1 (append (idlwave-recursive-directory-list dir) path1))
5013         ;; Keep unchanged
5014         (push dir path1)))
5015     (message "Expanding path...done")
5016     (nreverse path1)))
5017
5018 (defun idlwave-recursive-directory-list (dir)
5019   ;; Return a list of all directories below DIR, including DIR itself
5020   (let ((path (list dir)) path1 file files)
5021     (while (setq dir (pop path))
5022       (when (file-directory-p dir)
5023         (setq files (nreverse (directory-files dir t "[^.]")))
5024         (while (setq file (pop files))
5025           (if (file-directory-p file) 
5026               (push (file-name-as-directory file) path)))
5027         (push dir path1)))
5028     path1))
5029
5030
5031 ;;----- Scanning the library catalogs ------------------
5032
5033 (defun idlwave-scan-library-catalogs (&optional message-base no-load)
5034   "Scan for library catalog files (.idlwave_catalog) and ingest.  
5035
5036 All directories on `idlwave-path-alist' (or `idlwave-library-path'
5037 instead, if present) are searched.  Print MESSAGE-BASE along with the
5038 libraries being loaded, if passed, and skip loading/normalizing if
5039 NO-LOAD is non-nil.  The variable `idlwave-use-library-catalogs' can
5040 be set to nil to disable library catalog scanning."
5041   (when idlwave-use-library-catalogs
5042     (let ((dirs 
5043            (if idlwave-library-path
5044                (idlwave-expand-path idlwave-library-path)
5045              (mapcar 'car idlwave-path-alist)))
5046           (old-libname "")
5047           dir-entry dir flags catalog all-routines)
5048       (if message-base (message message-base))
5049       (while (setq dir (pop dirs))
5050         (catch 'continue
5051           (when (file-readable-p 
5052                  (setq catalog (expand-file-name ".idlwave_catalog" dir)))
5053             (unless no-load
5054               (setq idlwave-library-catalog-routines nil)
5055               ;; Load the catalog file
5056               (condition-case nil
5057                   (load catalog t t t)
5058                 (error (throw 'continue t)))
5059               (when (and 
5060                      message-base 
5061                      (not (string= idlwave-library-catalog-libname 
5062                                    old-libname)))
5063                 (message (concat message-base 
5064                                  idlwave-library-catalog-libname))
5065                 (setq old-libname idlwave-library-catalog-libname))
5066               (when idlwave-library-catalog-routines
5067                 (setq all-routines
5068                       (append 
5069                        (idlwave-sintern-rinfo-list
5070                         idlwave-library-catalog-routines 'sys dir)
5071                        all-routines))))
5072             
5073             ;;  Add a 'lib flag if on path-alist
5074             (when (and idlwave-path-alist
5075                        (setq dir-entry (assoc dir idlwave-path-alist)))
5076               (idlwave-path-alist-add-flag dir-entry 'lib)))))
5077       (unless no-load (setq idlwave-library-catalog-routines all-routines))
5078       (if message-base (message (concat message-base "done"))))))
5079
5080 ;;----- Communicating with the Shell -------------------
5081
5082 ;; First, here is the idl program which can be used to query IDL for
5083 ;; defined routines. 
5084 (defconst idlwave-routine-info.pro
5085   "
5086 ;; START OF IDLWAVE SUPPORT ROUTINES
5087 pro idlwave_print_info_entry,name,func=func,separator=sep
5088   ;; See if it's an object method
5089   if name eq '' then return
5090   func    = keyword_set(func) 
5091   methsep = strpos(name,'::')
5092   meth    = methsep ne -1
5093   
5094   ;; Get routine info
5095   pars   = routine_info(name,/parameters,functions=func)
5096   source = routine_info(name,/source,functions=func)
5097   nargs  = pars.num_args
5098   nkw    = pars.num_kw_args
5099   if nargs gt 0 then args = pars.args
5100   if nkw   gt 0 then kwargs = pars.kw_args
5101   
5102   ;; Trim the class, and make the name
5103   if meth then begin 
5104       class = strmid(name,0,methsep)
5105       name  = strmid(name,methsep+2,strlen(name)-1)
5106       if nargs gt 0 then begin 
5107           ;; remove the self argument
5108           wh = where(args ne 'SELF',nargs)
5109           if nargs gt 0 then args = args[wh]
5110       endif
5111   endif else begin
5112       ;; No class, just a normal routine.
5113       class = \"\"
5114   endelse
5115    
5116   ;; Calling sequence
5117   cs = \"\"
5118   if func then cs = 'Result = '
5119   if meth then cs = cs + 'Obj -> [' + '%s' + '::]'
5120   cs = cs + '%s'
5121   if func then cs = cs + '(' else if nargs gt 0 then cs = cs + ', '
5122   if nargs gt 0 then begin
5123       for j=0,nargs-1 do begin
5124           cs = cs + args[j]
5125           if j lt nargs-1 then cs = cs + ', '
5126       endfor
5127   end
5128   if func then cs = cs + ')'
5129   ;; Keyword arguments
5130   kwstring = ''
5131   if nkw gt 0 then begin
5132       for j=0,nkw-1 do begin
5133           kwstring = kwstring + ' ' + kwargs[j]
5134       endfor
5135   endif
5136   
5137   ret=(['IDLWAVE-PRO','IDLWAVE-FUN'])[func]
5138   
5139   print,ret + ': ' + name + sep + class + sep + source[0].path  $
5140     + sep + cs + sep + kwstring
5141 end
5142
5143 pro idlwave_routine_info
5144   on_error,1
5145   sep = '<@>'
5146   print,'>>>BEGIN OF IDLWAVE ROUTINE INFO (\"' + sep + '\" IS THE SEPARATOR)'
5147   all = routine_info()
5148   for i=0,n_elements(all)-1 do $
5149     idlwave_print_info_entry,all[i],separator=sep
5150   all = routine_info(/functions)
5151   for i=0,n_elements(all)-1 do $
5152     idlwave_print_info_entry,all[i],/func,separator=sep
5153   print,'>>>END OF IDLWAVE ROUTINE INFO'
5154 end
5155
5156 pro idlwave_get_sysvars
5157   on_error,1
5158   forward_function strjoin,strtrim,strsplit
5159   catch,error_status
5160   if error_status ne 0 then begin
5161       print, 'Cannot get info about system variables'
5162   endif else begin
5163       help,/brief,output=s,/system_variables  ; ? unsafe use of OUTPUT=
5164       s = strtrim(strjoin(s,' ',/single),2)   ; make one line
5165       v = strsplit(s,' +',/regex,/extract)    ; get variables
5166       for i=0,n_elements(v)-1 do begin
5167           t = ['']                            ; get tag list
5168           a=execute('if n_tags('+v[i]+') gt 0 then t=tag_names('+v[i]+')')
5169           print, 'IDLWAVE-SYSVAR: '+v[i]+' '+strjoin(t,' ',/single)
5170       endfor
5171   endelse
5172 end
5173
5174 pro idlwave_get_class_tags, class
5175   res = execute('tags=tag_names({'+class+'})')
5176   if res then print,'IDLWAVE-CLASS-TAGS: '+class+' '+strjoin(tags,' ',/single)
5177 end
5178 ;; END OF IDLWAVE SUPPORT ROUTINES
5179
5180   "The idl programs to get info from the shell.")
5181
5182 (defvar idlwave-idlwave_routine_info-compiled nil
5183   "Remembers if the routine info procedure is already compiled.")
5184
5185 (defvar idlwave-shell-temp-pro-file)
5186 (defvar idlwave-shell-temp-rinfo-save-file)
5187 (defun idlwave-shell-update-routine-info (&optional quiet run-hooks wait)
5188   "Query the shell for routine_info of compiled modules and update the lists."
5189   ;; Save and compile the procedure.  The compiled procedure is then
5190   ;; saved into an IDL SAVE file, to allow for fast RESTORE.
5191   ;; We need to RESTORE the procedure each time we use it, since
5192   ;; the user may have killed or redefined it.  In particular,
5193   ;; .RESET_SESSION will kill all user procedures.
5194   (unless (and idlwave-idlwave_routine_info-compiled
5195                (file-readable-p (idlwave-shell-temp-file 'rinfo)))
5196     (save-excursion
5197       (set-buffer (idlwave-find-file-noselect
5198                    (idlwave-shell-temp-file 'pro)))
5199       (erase-buffer)
5200       (insert idlwave-routine-info.pro)
5201       (save-buffer 0))
5202     (idlwave-shell-send-command 
5203      (concat ".run " idlwave-shell-temp-pro-file)
5204      nil 'hide wait)
5205 ;    (message "SENDING SAVE") ; ????????????????????????
5206     (idlwave-shell-send-command
5207      (format "save,'idlwave_routine_info','idlwave_print_info_entry',FILE='%s',/ROUTINES" 
5208              (idlwave-shell-temp-file 'rinfo))
5209      nil 'hide wait))
5210
5211   ;; Restore and execute the procedure, analyze the output
5212 ;  (message "SENDING RESTORE & EXECUTE") ; ????????????????????????
5213   (idlwave-shell-send-command
5214    (format "RESTORE, '%s' & idlwave_routine_info"
5215            idlwave-shell-temp-rinfo-save-file)
5216    `(progn
5217       (idlwave-shell-routine-info-filter)
5218       (idlwave-concatenate-rinfo-lists ,quiet ,run-hooks))
5219    'hide wait))
5220
5221 ;; ---------------------------------------------------------------------------
5222 ;;
5223 ;; Completion and displaying routine calling sequences
5224
5225 (defvar idlwave-completion-help-info nil)
5226 (defvar idlwave-completion-help-links nil)
5227 (defvar idlwave-current-obj_new-class nil)
5228 (defvar idlwave-complete-special nil)
5229
5230 (defun idlwave-complete (&optional arg module class)
5231   "Complete a function, procedure or keyword name at point.
5232 This function is smart and figures out what can be legally completed
5233 at this point.
5234 - At the beginning of a statement it completes procedure names.
5235 - In the middle of a statement it completes function names.
5236 - after a `(' or `,' in the argument list of a function or procedure,
5237   it completes a keyword of the relevant function or procedure.
5238 - In the first arg of `OBJ_NEW', it completes a class name.
5239
5240 When several completions are possible, a list will be displayed in the
5241 *Completions* buffer.  If this list is too long to fit into the
5242 window, scrolling can be achieved by repeatedly pressing
5243 \\[idlwave-complete].
5244
5245 The function also knows about object methods.  When it needs a class
5246 name, the action depends upon `idlwave-query-class', which see.  You
5247 can force IDLWAVE to ask you for a class name with a
5248 \\[universal-argument] prefix argument to this command.
5249
5250 See also the variables `idlwave-keyword-completion-adds-equal' and
5251 `idlwave-function-completion-adds-paren'.
5252
5253 The optional ARG can be used to specify the completion type in order
5254 to override IDLWAVE's idea of what should be completed at point.
5255 Possible values are:
5256
5257 0  <=>  query for the completion type
5258 1  <=>  'procedure
5259 2  <=>  'procedure-keyword
5260 3  <=>  'function
5261 4  <=>  'function-keyword
5262 5  <=>  'procedure-method
5263 6  <=>  'procedure-method-keyword
5264 7  <=>  'function-method
5265 8  <=>  'function-method-keyword
5266 9  <=>  'class
5267
5268 As a special case, the universal argument C-u forces completion of
5269 function names in places where the default would be a keyword.
5270
5271 Two prefix argument, C-u C-u, prompts for a regexp by which to limit
5272 completion.
5273
5274 For Lisp programmers only:
5275 When we force a keyword, optional argument MODULE can contain the module name.
5276 When we force a method or a method keyword, CLASS can specify the class."
5277   (interactive "P")
5278   (idlwave-routines)
5279   (let* ((where-list
5280           (if (and arg
5281                    (or (and (integerp arg) (not (equal arg '(16))))
5282                        (symbolp arg)))
5283               (idlwave-make-force-complete-where-list arg module class)
5284             (idlwave-where)))
5285          (what (nth 2 where-list))
5286          (idlwave-force-class-query (equal arg '(4)))
5287          (completion-regexp-list
5288           (if (equal arg '(16))
5289               (list (read-string (concat "Completion Regexp: "))))))
5290     
5291     (if (and module (string-match "::" module))
5292         (setq class (substring module 0 (match-beginning 0))
5293               module (substring module (match-end 0))))
5294
5295     (cond
5296
5297      ((and (null arg)
5298            (eq (car-safe last-command) 'idlwave-display-completion-list)
5299            (get-buffer-window "*Completions*"))
5300       (setq this-command last-command)
5301       (idlwave-scroll-completions))
5302
5303      ;; Check for any special completion functions
5304      ((and idlwave-complete-special
5305            (idlwave-call-special idlwave-complete-special)))
5306      
5307      ;; Complete a filename in quotes
5308      ((and (idlwave-in-quote)
5309            (not (eq what 'class)))
5310       (idlwave-complete-filename))
5311
5312      ((null what)
5313       (error "Nothing to complete here"))
5314
5315      ;; Complete a class
5316      ((eq what 'class)
5317       (setq idlwave-completion-help-info '(class))
5318       (idlwave-complete-class))
5319
5320      ((eq what 'procedure)
5321       ;; Complete a procedure name
5322       (let* ((cw-list (nth 3 where-list))
5323              (class-selector (idlwave-determine-class cw-list 'pro))
5324              (super-classes (unless (idlwave-explicit-class-listed cw-list)
5325                               (idlwave-all-class-inherits class-selector)))
5326              (isa (concat "procedure" (if class-selector "-method" "")))
5327              (type-selector 'pro))
5328         (setq idlwave-completion-help-info 
5329               (list 'routine nil type-selector class-selector nil super-classes))
5330         (idlwave-complete-in-buffer
5331          'procedure (if class-selector 'method 'routine)
5332          (idlwave-routines) 'idlwave-selector
5333          (format "Select a %s name%s"
5334                  isa
5335                  (if class-selector
5336                      (format " (class is %s)" 
5337                              (if (eq class-selector t) 
5338                                  "unknown" class-selector))
5339                    ""))
5340          isa
5341          'idlwave-attach-method-classes 'idlwave-add-file-link-selector)))
5342
5343      ((eq what 'function)
5344       ;; Complete a function name
5345       (let* ((cw-list (nth 3 where-list))
5346              (class-selector (idlwave-determine-class cw-list 'fun))
5347              (super-classes (unless (idlwave-explicit-class-listed cw-list)
5348                               (idlwave-all-class-inherits class-selector)))
5349              (isa (concat "function" (if class-selector "-method" "")))
5350              (type-selector 'fun))
5351         (setq idlwave-completion-help-info 
5352               (list 'routine nil type-selector class-selector nil super-classes))
5353         (idlwave-complete-in-buffer
5354          'function (if class-selector 'method 'routine)
5355          (idlwave-routines) 'idlwave-selector
5356          (format "Select a %s name%s"
5357                  isa
5358                  (if class-selector
5359                      (format " (class is %s)" 
5360                              (if (eq class-selector t)
5361                                  "unknown" class-selector))
5362                    ""))
5363          isa
5364          'idlwave-attach-method-classes 'idlwave-add-file-link-selector)))
5365
5366      ((and (memq what '(procedure-keyword function-keyword)) ; Special Case
5367            (equal arg '(4)))
5368       (idlwave-complete 3))
5369
5370      ((eq what 'procedure-keyword)
5371       ;; Complete a procedure keyword
5372       (let* ((where (nth 3 where-list))
5373              (name  (car where))
5374              (method-selector name)
5375              (type-selector 'pro)
5376              (class (idlwave-determine-class where 'pro))
5377              (class-selector class)
5378              (super-classes (idlwave-all-class-inherits class-selector))
5379              (isa (format "procedure%s-keyword" (if class "-method" "")))
5380              (entry (idlwave-best-rinfo-assq
5381                      name 'pro class (idlwave-routines)))
5382              (list (idlwave-entry-keywords entry 'do-link)))
5383         (unless (or entry (eq class t))
5384           (error "Nothing known about procedure %s"
5385                  (idlwave-make-full-name class name)))
5386         (setq list (idlwave-fix-keywords name 'pro class list super-classes))
5387         (unless list (error (format "No keywords available for procedure %s"
5388                                     (idlwave-make-full-name class name))))
5389         (setq idlwave-completion-help-info 
5390               (list 'keyword name type-selector class-selector entry super-classes))
5391         (idlwave-complete-in-buffer
5392          'keyword 'keyword list nil
5393          (format "Select keyword for procedure %s%s"
5394                  (idlwave-make-full-name class name)
5395                  (if (or (member '("_EXTRA") list)
5396                          (member '("_REF_EXTRA") list))                  
5397                      " (note _EXTRA)" ""))
5398          isa
5399          'idlwave-attach-keyword-classes)))
5400
5401      ((eq what 'function-keyword)
5402       ;; Complete a function keyword
5403       (let* ((where (nth 3 where-list))
5404              (name  (car where))
5405              (method-selector name)
5406              (type-selector 'fun)
5407              (class (idlwave-determine-class where 'fun))
5408              (class-selector class)
5409              (super-classes (idlwave-all-class-inherits class-selector))
5410              (isa (format "function%s-keyword" (if class "-method" "")))
5411              (entry (idlwave-best-rinfo-assq
5412                      name 'fun class (idlwave-routines)))
5413              (list (idlwave-entry-keywords entry 'do-link))
5414              msg-name)
5415         (unless (or entry (eq class t))
5416           (error "Nothing known about function %s"
5417                  (idlwave-make-full-name class name)))
5418         (setq list (idlwave-fix-keywords name 'fun class list super-classes))
5419         ;; OBJ_NEW: Messages mention the proper Init method
5420         (setq msg-name (if (and (null class)
5421                                 (string= (upcase name) "OBJ_NEW"))
5422                            (concat idlwave-current-obj_new-class
5423                                    "::Init (via OBJ_NEW)")
5424                          (idlwave-make-full-name class name)))
5425         (unless list (error (format "No keywords available for function %s"
5426                                     msg-name)))
5427         (setq idlwave-completion-help-info 
5428               (list 'keyword name type-selector class-selector nil super-classes))
5429         (idlwave-complete-in-buffer
5430          'keyword 'keyword list nil
5431          (format "Select keyword for function %s%s" msg-name
5432                  (if (or (member '("_EXTRA") list)
5433                          (member '("_REF_EXTRA") list))                  
5434                      " (note _EXTRA)" ""))
5435          isa
5436          'idlwave-attach-keyword-classes)))
5437
5438      (t (error "This should not happen (idlwave-complete)")))))
5439
5440 (defvar idlwave-complete-special nil
5441   "List of special completion functions.
5442 These functions are called for each completion.  Each function must
5443 check if its own special completion context is present.  If yes, it
5444 should use `idlwave-complete-in-buffer' to do some completion and
5445 return t.  If such a function returns t, *no further* attempts to
5446 complete other contexts will be done.  If the function returns nil,
5447 other completions will be tried.")
5448
5449 (defun idlwave-call-special (functions &rest args)
5450   (let ((funcs functions)
5451         fun ret)
5452     (catch 'exit
5453       (while (setq fun (pop funcs))
5454         (if (setq ret (apply fun args))
5455             (throw 'exit ret)))
5456       nil)))
5457
5458 (defun idlwave-make-force-complete-where-list (what &optional module class)
5459   ;; Return an artificial WHERE specification to force the completion
5460   ;; routine to complete a specific item independent of context.
5461   ;; WHAT is the prefix arg of `idlwave-complete', see there for details.
5462   ;; MODULE and CLASS can be used to specify the routine name and class.
5463   ;; The class name will also be found in MODULE if that is like "class::mod".
5464   (let* ((what-list '(("procedure") ("procedure-keyword")
5465                       ("function") ("function-keyword")
5466                       ("procedure-method") ("procedure-method-keyword")
5467                       ("function-method") ("function-method-keyword")
5468                       ("class")))
5469          (module (idlwave-sintern-routine-or-method module class))
5470          (class (idlwave-sintern-class class))
5471          (what (cond 
5472                 ((equal what 0)
5473                  (setq what
5474                        (intern (completing-read 
5475                                 "Complete what? " what-list nil t))))
5476                 ((integerp what)
5477                  (setq what (intern (car (nth (1- what) what-list)))))
5478                 ((and what
5479                       (symbolp what)
5480                       (assoc (symbol-name what) what-list))
5481                  what)
5482                 (t (error "Illegal WHAT"))))
5483          (nil-list '(nil nil nil nil))
5484          (class-list (list nil nil (or class t) nil)))
5485
5486     (cond
5487
5488      ((eq what 'procedure)
5489       (list nil-list nil-list 'procedure nil-list nil))
5490
5491      ((eq what 'procedure-keyword)
5492       (let* ((class-selector nil)
5493              (super-classes nil)
5494              (type-selector 'pro)
5495              (pro (or module
5496                       (idlwave-completing-read 
5497                        "Procedure: " (idlwave-routines) 'idlwave-selector))))
5498         (setq pro (idlwave-sintern-routine pro))
5499         (list nil-list nil-list 'procedure-keyword
5500               (list pro nil nil nil) nil)))
5501
5502      ((eq what 'function)
5503       (list nil-list nil-list 'function nil-list nil))
5504
5505      ((eq what 'function-keyword)
5506       (let* ((class-selector nil)
5507              (super-classes nil)
5508              (type-selector 'fun)
5509              (func (or module
5510                        (idlwave-completing-read 
5511                         "Function: " (idlwave-routines) 'idlwave-selector))))
5512         (setq func (idlwave-sintern-routine func))
5513         (list nil-list nil-list 'function-keyword
5514               (list func nil nil nil) nil)))
5515
5516      ((eq what 'procedure-method)
5517       (list nil-list nil-list 'procedure class-list nil))
5518
5519      ((eq what 'procedure-method-keyword)
5520       (let* ((class (idlwave-determine-class class-list 'pro))
5521              (class-selector class)
5522              (super-classes (idlwave-all-class-inherits class-selector))
5523              (type-selector 'pro)
5524              (pro (or module
5525                       (idlwave-completing-read
5526                        (format "Procedure in %s class: " class-selector)
5527                        (idlwave-routines) 'idlwave-selector))))
5528         (setq pro (idlwave-sintern-method pro))
5529         (list nil-list nil-list 'procedure-keyword
5530               (list pro nil class nil) nil)))
5531
5532      ((eq what 'function-method)
5533       (list nil-list nil-list 'function class-list nil))
5534
5535      ((eq what 'function-method-keyword)
5536       (let* ((class (idlwave-determine-class class-list 'fun))
5537              (class-selector class)
5538              (super-classes (idlwave-all-class-inherits class-selector))
5539              (type-selector 'fun)
5540              (func (or module
5541                        (idlwave-completing-read
5542                         (format "Function in %s class: " class-selector)
5543                         (idlwave-routines) 'idlwave-selector))))
5544         (setq func (idlwave-sintern-method func))
5545         (list nil-list nil-list 'function-keyword
5546               (list func nil class nil) nil)))
5547
5548      ((eq what 'class)
5549       (list nil-list nil-list 'class nil-list nil))
5550      
5551      (t (error "Illegal value for WHAT")))))
5552
5553 (defun idlwave-completing-read (&rest args)
5554   ;; Completing read, case insensitive
5555   (let ((old-value (default-value 'completion-ignore-case)))
5556     (unwind-protect
5557         (progn
5558           (setq-default completion-ignore-case t)
5559           (apply 'completing-read args))
5560       (setq-default completion-ignore-case old-value))))
5561
5562 (defvar idlwave-shell-default-directory)
5563 (defun idlwave-complete-filename ()
5564   "Use the comint stuff to complete a file name."
5565   (require 'comint)
5566   (let* ((comint-file-name-chars "~/A-Za-z0-9+@:_.$#%={}\\-")
5567          (comint-completion-addsuffix nil)
5568          (default-directory
5569            (if (and (boundp 'idlwave-shell-default-directory)
5570                     (stringp idlwave-shell-default-directory)
5571                     (file-directory-p idlwave-shell-default-directory))
5572                idlwave-shell-default-directory
5573              default-directory)))          
5574     (comint-dynamic-complete-filename)))
5575
5576 (defun idlwave-make-full-name (class name)
5577   ;; Make a fully qualified module name including the class name
5578   (concat (if class (format "%s::" class) "") name))
5579
5580 (defun idlwave-rinfo-assoc (name type class list)
5581   "Like `idlwave-rinfo-assq', but sintern strings first."
5582   (idlwave-rinfo-assq 
5583    (idlwave-sintern-routine-or-method name class)
5584    type (idlwave-sintern-class class) list))
5585
5586 (defun idlwave-rinfo-assq (name type class list)
5587   ;; Works like assq, but also checks type and class
5588   (catch 'exit
5589     (let (match)
5590       (while (setq match (assq name list))
5591         (and (or (eq type t)
5592                  (eq (nth 1 match) type))
5593              (eq (nth 2 match) class)
5594              (throw 'exit match))
5595         (setq list (cdr (memq match list)))))))
5596
5597 (defun idlwave-rinfo-assq-any-class (name type class list)
5598   ;; Return the first matching method on the inheritance list
5599   (let* ((classes (cons class (idlwave-all-class-inherits class)))
5600          class rtn)
5601     (while classes
5602       (if (setq rtn (idlwave-rinfo-assq name type (pop classes) list))
5603           (setq classes nil)))
5604     rtn))
5605
5606 (defun idlwave-best-rinfo-assq (name type class list &optional with-file)
5607   "Like `idlwave-rinfo-assq', but get all twins and sort, then return first.
5608 If WITH-FILE is passed, find the best rinfo entry with a file included."
5609   (let ((twins (idlwave-routine-twins
5610                 (idlwave-rinfo-assq-any-class name type class list)
5611                 list))
5612         syslibp)
5613     (when (> (length twins) 1)
5614       (setq twins (sort twins 'idlwave-routine-entry-compare-twins))
5615       (if (and (eq 'system (car (nth 3 (car twins))))
5616                (setq syslibp (idlwave-any-syslib (cdr twins)))
5617                (not (equal 1 syslibp)))
5618           ;; Its a syslib, so we need to remove the system entry
5619           (setq twins (cdr twins)))
5620       (if with-file
5621           (setq twins (delq nil
5622                             (mapcar (lambda (x)
5623                                       (if (nth 1 (nth 3 x)) x))
5624                                     twins)))))
5625     (car twins)))
5626
5627 (defun idlwave-best-rinfo-assoc (name type class list)
5628   "Like `idlwave-best-rinfo-assq', but sintern strings first."
5629   (idlwave-best-rinfo-assq
5630    (idlwave-sintern-routine-or-method name class)
5631    type (idlwave-sintern-class class) list))
5632
5633 (defun idlwave-any-syslib (entries)
5634   "Does the entry list ENTRIES contain a syslib entry?
5635 If yes, return the index (>=1)."
5636   (let (file (cnt 0))
5637     (catch 'exit
5638       (while entries
5639         (incf cnt)
5640         (setq file (idlwave-routine-source-file (nth 3 (car entries))))
5641         (if (and file (idlwave-syslib-p file))
5642             (throw 'exit cnt)
5643           (setq entries (cdr entries))))
5644       nil)))
5645
5646 (defun idlwave-all-assq (key list)
5647   "Return a list of all associations of Key in LIST."
5648   (let (rtn elt)
5649     (while (setq elt (assq key list))
5650       (push elt rtn)
5651       (setq list (cdr (memq elt list))))
5652     (nreverse rtn)))
5653
5654 (defun idlwave-all-method-classes (method &optional type)
5655   "Return all classes which have a method METHOD.  TYPE is 'fun or 'pro.
5656 When TYPE is not specified, both procedures and functions will be considered."
5657   (if (null method)
5658       (mapcar 'car (idlwave-class-alist))
5659     (let (rtn)
5660       (mapcar (lambda (x)
5661                 (and (nth 2 x)
5662                      (or (not type)
5663                          (eq type (nth 1 x)))
5664                      (push (nth 2 x) rtn)))
5665               (idlwave-all-assq method (idlwave-routines)))
5666       (idlwave-uniquify rtn))))
5667
5668 (defun idlwave-all-method-keyword-classes (method keyword &optional type)
5669   "Return all classes which have a method METHOD with keyword KEYWORD.
5670 TYPE is 'fun or 'pro.
5671 When TYPE is not specified, both procedures and functions will be considered."
5672   (if (or (null method)
5673           (null keyword))
5674       nil
5675     (let (rtn)
5676       (mapcar (lambda (x)
5677                 (and (nth 2 x)           ; non-nil class
5678                      (or (not type)      ; correct or unspecified type
5679                          (eq type (nth 1 x)))
5680                      (assoc keyword (idlwave-entry-keywords x))
5681                      (push (nth 2 x) rtn)))
5682               (idlwave-all-assq method (idlwave-routines)))
5683       (idlwave-uniquify rtn))))
5684
5685 (defun idlwave-members-only (list club)
5686   "Return list of all elements in LIST which are also in CLUB."
5687   (let (rtn)
5688     (while list
5689       (if (member (car list) club)
5690           (setq rtn (cons (car list) rtn)))
5691       (setq list (cdr list)))
5692     (nreverse rtn)))
5693
5694 (defun idlwave-nonmembers-only (list club)
5695   "Return list of all elements in LIST which are not in CLUB."
5696   (let (rtn)
5697     (while list
5698       (if (member (car list) club)
5699           nil
5700         (setq rtn (cons (car list) rtn)))
5701       (setq list (cdr list)))
5702     (nreverse rtn)))
5703
5704 (defun idlwave-explicit-class-listed (info)
5705   "Return whether or not the class is listed explicitly, ala a->b::c.
5706 INFO is as returned by idlwave-what-function or -procedure."
5707   (let ((apos (nth 3 info)))
5708     (if apos
5709         (save-excursion (goto-char apos)
5710                         (looking-at "->[a-zA-Z][a-zA-Z0-9$_]*::")))))
5711
5712 (defvar idlwave-determine-class-special nil
5713   "List of special functions for determining class.
5714 Must accept two arguments: `apos' and `info'")
5715
5716 (defun idlwave-determine-class (info type)
5717   ;; Determine the class of a routine call.  
5718   ;; INFO is the `cw-list' structure as returned by idlwave-where.
5719   ;; The second element in this structure is the class.  When nil, we
5720   ;; return nil.  When t, try to get the class from text properties at
5721   ;; the arrow.  When the object is "self", we use the class of the
5722   ;; current routine.  otherwise prompt the user for a class name.
5723   ;; Also stores the selected class as a text property at the arrow.
5724   ;; TYPE is 'fun or 'pro.
5725   (let* ((class (nth 2 info))
5726          (apos (nth 3 info))
5727          (nassoc (assoc (if (stringp (car info))
5728                             (upcase (car info))
5729                           (car info))
5730                         idlwave-query-class))
5731          (dassoc (assq (if (car info) 'keyword-default 'method-default)
5732                        idlwave-query-class))
5733          (query (cond (nassoc (cdr nassoc))
5734                       (dassoc (cdr dassoc))
5735                       (t t)))
5736          (arrow (and apos (string= (buffer-substring apos (+ 2 apos)) "->")))
5737          (is-self 
5738           (and arrow
5739                (save-excursion (goto-char apos)
5740                                (forward-word -1)
5741                                (let ((case-fold-search t))
5742                                  (looking-at "self\\>")))))
5743          (force-query idlwave-force-class-query)
5744          store special-class class-alist)
5745     (cond
5746      ((null class) nil)
5747      ((eq t class)
5748       ;; There is an object which would like to know its class
5749       (if (and arrow (get-text-property apos 'idlwave-class)
5750                idlwave-store-inquired-class
5751                (not force-query))
5752           (setq class (get-text-property apos 'idlwave-class)
5753                 class (idlwave-sintern-class class)))
5754       (if (and (eq t class) is-self)
5755           (setq class (or (nth 2 (idlwave-current-routine)) class)))
5756
5757       ;; Before prompting, try any special class determination routines
5758       (when (and (eq t class) 
5759                  idlwave-determine-class-special
5760                  (not force-query))
5761         (setq special-class 
5762               (idlwave-call-special idlwave-determine-class-special apos))
5763         (if special-class 
5764             (setq class (idlwave-sintern-class special-class)
5765                   store idlwave-store-inquired-class)))
5766       
5767       ;; Prompt for a class, if we need to
5768       (when (and (eq class t)
5769                  (or force-query query))
5770         (setq class-alist 
5771               (mapcar 'list (idlwave-all-method-classes (car info) type)))
5772         (setq class
5773               (idlwave-sintern-class
5774                (cond
5775                 ((and (= (length class-alist) 0) (not force-query))
5776                  (error "No classes available with method %s" (car info)))
5777                 ((and (= (length class-alist) 1) (not force-query))
5778                  (car (car class-alist)))
5779                 (t 
5780                  (setq store idlwave-store-inquired-class)
5781                  (idlwave-completing-read 
5782                   (format "Class%s: " (if (stringp (car info))
5783                                           (format " for %s method %s"
5784                                                   type (car info))
5785                                         ""))
5786                   class-alist nil nil nil 'idlwave-class-history))))))
5787
5788       ;; Store it, if requested
5789       (when (and class (not (eq t class)))
5790         ;; We have a real class here
5791         (when (and store arrow)
5792           (condition-case ()
5793               (add-text-properties 
5794                apos (+ apos 2) 
5795                `(idlwave-class ,class face ,idlwave-class-arrow-face 
5796                                rear-nonsticky t))
5797             (error nil)))
5798         (setf (nth 2 info) class))
5799       ;; Return the class
5800       class)
5801      ;; Default as fallback
5802      (t class))))
5803
5804 (defvar type-selector)
5805 (defvar class-selector)
5806 (defvar method-selector)
5807 (defvar super-classes)
5808 (defun idlwave-selector (a)
5809   (and (eq (nth 1 a) type-selector)
5810        (or (and (nth 2 a) (eq class-selector t))
5811            (eq (nth 2 a) class-selector)
5812            (memq (nth 2 a) super-classes))))
5813
5814 (defun idlwave-add-file-link-selector (a)
5815   ;; Record a file link, if any, for the tested names during selection.
5816   (let ((sel (idlwave-selector a)) file)
5817     (if (and sel (setq file (idlwave-entry-has-help a)))
5818         (push (cons (car a) file) idlwave-completion-help-links))
5819     sel))
5820
5821
5822 (defun idlwave-where ()
5823   "Find out where we are. 
5824 The return value is a list with the following stuff:
5825 \(PRO-LIST FUNC-LIST COMPLETE-WHAT CW-LIST LAST-CHAR)
5826
5827 PRO-LIST       (PRO POINT CLASS ARROW)
5828 FUNC-LIST      (FUNC POINT CLASS ARROW)
5829 COMPLETE-WHAT  a symbol indicating what kind of completion makes sense here
5830 CW-LIST        (PRO-OR-FUNC POINT CLASS ARROW)  Like PRO-LIST, for what can 
5831                be completed here.
5832 LAST-CHAR      last relevant character before point (non-white non-comment,
5833                not part of current identifier or leading slash).
5834
5835 In the lists, we have these meanings:
5836 PRO:    Procedure name
5837 FUNC:   Function name
5838 POINT:  Where is this
5839 CLASS:  What class has the routine (nil=no, t=is method, but class unknown)
5840 ARROW:  Location of the arrow"
5841   (idlwave-routines)
5842   (let* (;(bos (save-excursion (idlwave-beginning-of-statement) (point))) 
5843          (bos (save-excursion (idlwave-start-of-substatement 'pre) (point)))
5844          (func-entry (idlwave-what-function bos))
5845          (func (car func-entry))
5846          (func-class (nth 1 func-entry))
5847          (func-arrow (nth 2 func-entry))
5848          (func-point (or (nth 3 func-entry) 0))
5849          (func-level (or (nth 4 func-entry) 0))
5850          (pro-entry (idlwave-what-procedure bos))
5851          (pro (car pro-entry))
5852          (pro-class (nth 1 pro-entry))
5853          (pro-arrow (nth 2 pro-entry))
5854          (pro-point (or (nth 3 pro-entry) 0))
5855          (last-char (idlwave-last-valid-char))
5856          (case-fold-search t)
5857          cw cw-mod cw-arrow cw-class cw-point)
5858     (if (< func-point pro-point) (setq func nil))
5859     (cond
5860      ((string-match "\\`[ \t]*\\(pro\\|function\\)[ \t]+[a-zA-Z0-9_]*\\'"
5861                     (buffer-substring bos (point)))
5862       (setq cw 'class))
5863      ((string-match 
5864        "\\`[ \t]*\\([a-zA-Z][a-zA-Z0-9$_]*\\)?\\'" 
5865        (buffer-substring (if (> pro-point 0) pro-point bos) (point)))
5866       (setq cw 'procedure cw-class pro-class cw-point pro-point
5867             cw-arrow pro-arrow))
5868      ((string-match "\\`[ \t]*\\(pro\\|function\\)\\>"
5869                     (buffer-substring bos (point)))
5870       nil)
5871      ((string-match "OBJ_NEW([ \t]*['\"]\\([a-zA-Z0-9$_]*\\)?\\'"
5872                     (buffer-substring bos (point)))
5873       (setq cw 'class))                    
5874      ((string-match "\\<inherits\\s-+\\([a-zA-Z0-9$_]*\\)?\\'"
5875                     (buffer-substring bos (point)))
5876       (setq cw 'class))                    
5877      ((and func 
5878            (> func-point pro-point)
5879            (= func-level 1)
5880            (memq last-char '(?\( ?,)))
5881       (setq cw 'function-keyword cw-mod func cw-point func-point
5882             cw-class func-class cw-arrow func-arrow))
5883      ((and pro (eq last-char ?,))
5884       (setq cw 'procedure-keyword cw-mod pro cw-point pro-point
5885             cw-class pro-class cw-arrow pro-arrow))
5886 ;     ((member last-char '(?\' ?\) ?\] ?!))
5887 ;      ;; after these chars, a function makes no sense
5888 ;      ;; FIXME: I am sure there can be more in this list
5889 ;      ;; FIXME: Do we want to do this at all?
5890 ;      nil)
5891      ;; Everywhere else we try a function.
5892      (t
5893       (setq cw 'function)
5894       (save-excursion
5895         (if (re-search-backward "->[ \t]*\\(\\([$a-zA-Z0-9_]+\\)::\\)?[$a-zA-Z0-9_]*\\=" bos t)
5896             (setq cw-arrow (copy-marker (match-beginning 0))
5897                   cw-class (if (match-end 2)
5898                                (idlwave-sintern-class (match-string 2))
5899                              t))))))
5900     (list (list pro pro-point pro-class pro-arrow)
5901           (list func func-point func-class func-arrow)
5902           cw
5903           (list cw-mod cw-point cw-class cw-arrow)
5904           last-char)))
5905
5906 (defun idlwave-this-word (&optional class)
5907   ;; Grab the word around point.  CLASS is for the `skip-chars=...' functions
5908   (setq class (or class "a-zA-Z0-9$_"))
5909   (save-excursion
5910     (buffer-substring
5911      (progn (skip-chars-backward class) (point))
5912      (progn (skip-chars-forward  class) (point)))))
5913
5914 (defun idlwave-what-function (&optional bound)
5915   ;; Find out if point is within the argument list of a function.
5916   ;; The return value is ("function-name" class arrow-start (point) level).
5917   ;; Level is 1 on the top level parentheses, higher further down.
5918
5919   ;; If the optional BOUND is an integer, bound backwards directed
5920   ;;    searches to this point.
5921
5922   (catch 'exit
5923     (let (pos 
5924           func-point
5925           (cnt 0)
5926           func arrow-start class)
5927       (idlwave-with-special-syntax
5928        (save-restriction
5929          (save-excursion
5930            (narrow-to-region (max 1 (or bound 0)) (point-max))
5931            ;; move back out of the current parenthesis
5932            (while (condition-case nil
5933                       (progn (up-list -1) t)
5934                     (error nil))
5935              (setq pos (point))
5936              (incf cnt)
5937              (when (and (= (following-char) ?\()
5938                         (re-search-backward 
5939                          "\\(::\\|\\<\\)\\([a-zA-Z][a-zA-Z0-9$_]*\\)[ \t]*\\="
5940                          bound t))
5941                (setq func (match-string 2)
5942                      func-point (goto-char (match-beginning 2))
5943                      pos func-point)
5944                (if (re-search-backward 
5945                     "->[ \t]*\\(\\([a-zA-Z][a-zA-Z0-9$_]*\\)::\\)?\\=" bound t)
5946                    (setq arrow-start (copy-marker (match-beginning 0))
5947                          class (or (match-string 2) t)))
5948                (throw 
5949                 'exit 
5950                 (list
5951                  (idlwave-sintern-routine-or-method func class)
5952                  (idlwave-sintern-class class)
5953                  arrow-start func-point cnt)))
5954              (goto-char pos))
5955            (throw 'exit nil)))))))
5956
5957 (defun idlwave-what-procedure (&optional bound)
5958   ;; Find out if point is within the argument list of a procedure.
5959   ;; The return value is ("procedure-name" class arrow-pos (point)).
5960
5961   ;; If the optional BOUND is an integer, bound backwards directed
5962   ;;    searches to this point.
5963   (let ((pos (point)) pro-point
5964         pro class arrow-start string)
5965     (save-excursion 
5966       ;;(idlwave-beginning-of-statement)
5967       (idlwave-start-of-substatement 'pre)
5968       (setq string (buffer-substring (point) pos))
5969       (if (string-match 
5970            "\\`[ \t]*\\([a-zA-Z][a-zA-Z0-9$_]*\\)[ \t]*\\(,\\|\\'\\)" string)
5971           (setq pro (match-string 1 string)
5972                 pro-point (+ (point) (match-beginning 1)))
5973         (if (and (idlwave-skip-object)
5974                  (setq string (buffer-substring (point) pos))
5975                  (string-match 
5976                   "\\`[ \t]*\\(->\\)[ \t]*\\(\\([a-zA-Z][a-zA-Z0-9$_]*\\)::\\)?\\([a-zA-Z][a-zA-Z0-9$_]*\\)?[ \t]*\\(,\\|\\'\\)" string))
5977             (setq pro (if (match-beginning 4)
5978                           (match-string 4 string))
5979                   pro-point (if (match-beginning 4)
5980                                 (+ (point) (match-beginning 4))
5981                         pos)
5982                   arrow-start (copy-marker (+ (point) (match-beginning 1)))
5983                   class (or (match-string 3 string) t)))))
5984     (list (idlwave-sintern-routine-or-method pro class)
5985           (idlwave-sintern-class class)
5986           arrow-start
5987           pro-point)))
5988
5989 (defun idlwave-skip-object ()
5990   ;; If there is an object at point, move over it and return t.
5991   (let ((pos (point)))
5992     (if (catch 'exit
5993           (save-excursion
5994             (skip-chars-forward "       ")  ; white space
5995             (skip-chars-forward "*")        ; de-reference
5996             (cond
5997              ((looking-at idlwave-identifier)
5998               (goto-char (match-end 0)))
5999              ((eq (following-char) ?\()
6000               nil)
6001              (t (throw 'exit nil)))
6002             (catch 'endwhile
6003               (while t
6004                 (cond ((eq (following-char) ?.)
6005                        (forward-char 1)
6006                        (if (not (looking-at idlwave-identifier))
6007                            (throw 'exit nil))
6008                        (goto-char (match-end 0)))
6009                       ((memq (following-char) '(?\( ?\[))
6010                        (condition-case nil
6011                            (forward-list 1)
6012                          (error (throw 'exit nil))))
6013                       (t (throw 'endwhile t)))))
6014             (if (looking-at "[ \t]*->")
6015                 (throw 'exit (setq pos (match-beginning 0)))
6016               (throw 'exit nil))))
6017         (goto-char pos)
6018       nil)))
6019   
6020 (defun idlwave-last-valid-char ()
6021   "Return the last character before point which is not white or a comment
6022 and also not part of the current identifier.  Since we do this in
6023 order to identify places where keywords are, we consider the initial
6024 `/' of a keyword as part of the identifier.
6025 This function is not general, can only be used for completion stuff."
6026   (catch 'exit
6027     (save-excursion
6028       ;; skip the current identifier
6029       (skip-chars-backward "a-zA-Z0-9_$")
6030       ;; also skip a leading slash which might be belong to the keyword
6031       (if (eq (preceding-char) ?/)
6032           (backward-char 1))
6033       ;; FIXME: does not check if this is a valid identifier
6034       (while t
6035         (skip-chars-backward " \t")
6036         (cond
6037          ((memq (preceding-char) '(?\; ?\$)) (throw 'exit nil))
6038          ((eq (preceding-char) ?\n)
6039           (beginning-of-line 0)
6040           (if (looking-at "\\([^;\n]*\\)\\$[ \t]*\\(;[^\n]*\\)?\n")
6041               ;; continuation line
6042               (goto-char (match-end 1))
6043             (throw 'exit nil)))
6044          (t (throw 'exit (preceding-char))))))))
6045
6046 (defvar idlwave-complete-after-success-form nil
6047   "A form to evaluate after successful completion.")
6048 (defvar idlwave-complete-after-success-form-force nil
6049   "A form to evaluate after completion selection in *Completions* buffer.")
6050 (defconst idlwave-completion-mark (make-marker)
6051   "A mark pointing to the beginning of the completion string.")
6052
6053 (defun idlwave-complete-in-buffer (type stype list selector prompt isa
6054                                         &optional prepare-display-function
6055                                         special-selector)
6056   "Perform TYPE completion of word before point against LIST.
6057 SELECTOR is the PREDICATE argument for the completion function.  Show
6058 PROMPT in echo area.  TYPE is one of 'function, 'procedure,
6059 'class-tag, or 'keyword.  SPECIAL-SELECTOR is used only once, for
6060 `all-completions', and can be used to, e.g., accumulate information on
6061 matching completions."
6062   (let* ((completion-ignore-case t)
6063          beg (end (point)) slash part spart completion all-completions
6064          dpart dcompletion)
6065
6066     (unless list
6067       (error (concat prompt ": No completions available")))
6068
6069     ;; What is already in the buffer?
6070     (save-excursion
6071       (skip-chars-backward "a-zA-Z0-9_$")
6072       (setq slash (eq (preceding-char) ?/)
6073             beg (point)
6074             idlwave-complete-after-success-form
6075             (list 'idlwave-after-successful-completion
6076                   (list 'quote type) slash beg)
6077             idlwave-complete-after-success-form-force
6078             (list 'idlwave-after-successful-completion
6079                   (list 'quote type) slash (list 'quote 'force))))
6080
6081     ;; Try a completion
6082     (setq part (buffer-substring beg end)
6083           dpart (downcase part)
6084           spart (idlwave-sintern stype part)
6085           completion (try-completion part list selector)
6086           dcompletion (if (stringp completion) (downcase completion))
6087           idlwave-completion-help-links nil)
6088     (cond
6089      ((null completion)
6090       ;; nothing available.
6091       (error (concat prompt ": no completion for \"%s\"") part))
6092      ((and (not (equal dpart dcompletion))
6093            (not (eq t completion)))
6094       ;; We can add something
6095       (delete-region beg end)
6096       (if (and (string= part dpart)
6097                (or (not (string= part ""))
6098                    idlwave-complete-empty-string-as-lower-case)
6099                (not idlwave-completion-force-default-case))
6100           (insert dcompletion)
6101         (insert completion))
6102       (if (eq t (try-completion completion list selector))
6103           ;; Now this is a unique match
6104           (idlwave-after-successful-completion type slash beg))
6105       t)
6106      ((or (eq completion t)
6107           (and (= 1 (length (setq all-completions
6108                                   (idlwave-uniquify
6109                                    (all-completions part list 
6110                                                     (or special-selector 
6111                                                         selector))))))
6112                (equal dpart dcompletion)))
6113       ;; This is already complete
6114       (idlwave-after-successful-completion type slash beg)
6115       (message "%s is already the complete %s" part isa)
6116       nil)
6117      (t        
6118       ;; We cannot add something - offer a list.
6119       (message "Making completion list...")
6120       
6121       (unless idlwave-completion-help-links ; already set somewhere?
6122         (mapcar (lambda (x)  ; Pass link prop through to highlight-linked
6123                   (let ((link (get-text-property 0 'link (car x))))
6124                     (if link
6125                         (push (cons (car x) link) 
6126                               idlwave-completion-help-links))))
6127                 list))
6128       (let* ((list all-completions)
6129              ;; "complete" means, this is already a valid completion
6130              (complete (memq spart all-completions))
6131              (completion-highlight-first-word-only t)) ; XEmacs
6132 ;            (completion-fixup-function               ; Emacs
6133 ;             (lambda () (and (eq (preceding-char) ?>)
6134 ;                             (re-search-backward " <" beg t)))))
6135              
6136         (setq list (sort list (lambda (a b)
6137                                 (string< (downcase a) (downcase b)))))
6138         (if prepare-display-function
6139             (setq list (funcall prepare-display-function list)))
6140         (if (and (string= part dpart)
6141                  (or (not (string= part ""))
6142                      idlwave-complete-empty-string-as-lower-case)
6143                  (not idlwave-completion-force-default-case))
6144             (setq list (mapcar (lambda (x)
6145                                  (if (listp x) 
6146                                      (setcar x (downcase (car x)))
6147                                    (setq x (downcase x)))
6148                                  x)
6149                                list)))
6150         (idlwave-display-completion-list list prompt beg complete))
6151       t))))
6152
6153 (defun idlwave-complete-class ()
6154   "Complete a class at point."
6155   (interactive)
6156   ;; Call `idlwave-routines' to make sure the class list will be available
6157   (idlwave-routines)
6158   ;; Check for the special case of completing empty string after pro/function
6159   (if (let ((case-fold-search t))
6160         (save-excursion
6161           (and
6162            (re-search-backward "\\<\\(pro\\|function\\)[ \t]+\\="
6163                                (- (point) 15) t)
6164            (goto-char (point-min))
6165            (re-search-forward 
6166             "^[ \t]*\\(pro\\|function\\)[ \t]+\\([a-zA-Z0-9_]+::\\)" nil t))))
6167       ;; Yank the full class specification
6168       (insert (match-string 2))
6169     ;; Do the completion, using list gathered from `idlwave-routines'
6170     (idlwave-complete-in-buffer 
6171      'class 'class (idlwave-class-alist) nil 
6172      "Select a class" "class"
6173      '(lambda (list)  ;; Push it to help-links if system help available
6174         (mapcar (lambda (x)
6175                   (let* ((entry (idlwave-class-info x))
6176                          (link (nth 1 (assq 'link entry))))
6177                     (if link (push (cons x link) 
6178                                    idlwave-completion-help-links))
6179                     x))
6180                 list)))))
6181
6182 (defun idlwave-attach-classes (list type show-classes)
6183   ;; Attach the proper class list to a LIST of completion items.
6184   ;; TYPE, when 'kwd, shows classes for method keywords, when
6185   ;; 'class-tag, for class tags, and otherwise for methods.
6186   ;; SHOW-CLASSES is the value of `idlwave-completion-show-classes'.
6187   (if (or (null show-classes)           ; don't want to see classes
6188           (null class-selector)         ; not a method call
6189           (and 
6190            (stringp class-selector) ; the class is already known
6191            (not super-classes)))    ; no possibilities for inheritance
6192       ;; In these cases, we do not have to do anything
6193       list
6194     (let* ((do-prop (and (>= show-classes 0)
6195                          (>= emacs-major-version 21)))
6196            (do-buf (not (= show-classes 0)))
6197            ;; (do-dots (featurep 'xemacs))
6198            (do-dots t)
6199            (inherit (if (and (not (eq type 'class-tag)) super-classes)
6200                         (cons class-selector super-classes)))
6201            (max (abs show-classes))
6202            (lmax (if do-dots (apply 'max (mapcar 'length list))))
6203           classes nclasses class-info space)
6204       (mapcar 
6205        (lambda (x)
6206          ;; get the classes
6207          (if (eq type 'class-tag)
6208              ;; Just one class for tags
6209              (setq classes
6210                    (list 
6211                     (idlwave-class-or-superclass-with-tag class-selector x)))
6212            ;; Multiple classes for method or method-keyword
6213            (setq classes
6214                  (if (eq type 'kwd)
6215                      (idlwave-all-method-keyword-classes
6216                       method-selector x type-selector)
6217                    (idlwave-all-method-classes x type-selector)))
6218            (if inherit
6219                (setq classes 
6220                      (delq nil
6221                            (mapcar (lambda (x) (if (memq x inherit) x nil))
6222                                    classes)))))
6223          (setq nclasses (length classes))
6224          ;; Make the separator between item and class-info
6225          (if do-dots
6226              (setq space (concat " " (make-string (- lmax (length x)) ?.)))
6227            (setq space " "))
6228          (if  do-buf
6229              ;; We do want info in the buffer
6230              (if (<= nclasses max)
6231                  (setq class-info (concat
6232                                    space
6233                                    "<" (mapconcat 'identity classes ",") ">"))
6234                (setq class-info (format "%s<%d classes>" space nclasses)))
6235            (setq class-info nil))
6236          (when do-prop
6237            ;; We do want properties
6238            (setq x (copy-sequence x))
6239            (put-text-property 0 (length x)
6240                               'help-echo (mapconcat 'identity classes " ")
6241                               x))
6242          (if class-info
6243              (list x class-info)
6244            x))
6245        list))))
6246
6247 (defun idlwave-attach-method-classes (list)
6248   ;; Call idlwave-attach-classes with method parameters
6249   (idlwave-attach-classes list 'method idlwave-completion-show-classes))
6250 (defun idlwave-attach-keyword-classes (list)
6251   ;; Call idlwave-attach-classes with keyword parameters
6252   (idlwave-attach-classes list 'kwd idlwave-completion-show-classes))
6253 (defun idlwave-attach-class-tag-classes (list)
6254   ;; Call idlwave-attach-classes with class structure tags
6255   (idlwave-attach-classes list 'class-tag idlwave-completion-show-classes))
6256                                         
6257
6258 ;;----------------------------------------------------------------------
6259 ;;----------------------------------------------------------------------
6260 ;;----------------------------------------------------------------------
6261 ;;----------------------------------------------------------------------
6262 ;;----------------------------------------------------------------------
6263 (defvar rtn)
6264 (defun idlwave-pset (item)
6265   (set 'rtn item))
6266
6267 (defun idlwave-popup-select (ev list title &optional sort)
6268   "Select an item in LIST with a popup menu.
6269 TITLE is the title to put atop the popup.  If SORT is non-nil,
6270 sort the list before displaying"
6271   (let ((maxpopup idlwave-max-popup-menu-items)
6272         rtn menu resp)
6273     (cond ((null list))
6274           ((= 1 (length list))
6275            (setq rtn (car list)))
6276           ((featurep 'xemacs)
6277            (if sort (setq list (sort list (lambda (a b) 
6278                                             (string< (upcase a) (upcase b))))))
6279            (setq menu
6280                  (append (list title)
6281                          (mapcar (lambda (x) (vector x (list 'idlwave-pset
6282                                                              x)))
6283                                  list)))
6284            (setq menu (idlwave-split-menu-xemacs menu maxpopup))
6285            (setq resp (get-popup-menu-response menu))
6286            (funcall (event-function resp) (event-object resp)))
6287           (t
6288            (if sort (setq list (sort list (lambda (a b) 
6289                                             (string< (upcase a) (upcase b))))))
6290            (setq menu (cons title
6291                             (list
6292                              (append (list "")
6293                                      (mapcar (lambda(x) (cons x x)) list)))))
6294            (setq menu (idlwave-split-menu-emacs menu maxpopup))
6295            (setq rtn (x-popup-menu ev menu))))
6296     rtn))
6297
6298 (defun idlwave-split-menu-xemacs (menu N)
6299   "Split the MENU into submenus of maximum length N."
6300   (if (<= (length menu) (1+ N))
6301       ;; No splitting needed
6302       menu
6303     (let* ((title (car menu))
6304            (entries (cdr menu))
6305            (menu (list title))
6306            (cnt 0)
6307            (nextmenu nil))
6308       (while entries
6309         (while (and entries (< cnt N))
6310           (setq cnt (1+ cnt)
6311                 nextmenu (cons (car entries) nextmenu)
6312                 entries (cdr entries)))
6313         (setq nextmenu (nreverse nextmenu))
6314         (setq nextmenu (cons (format "%s...%s"
6315                                      (aref (car nextmenu) 0)
6316                                      (aref (nth (1- cnt) nextmenu) 0))
6317                              nextmenu))
6318         (setq menu (cons nextmenu menu)
6319               nextmenu nil
6320               cnt 0))
6321       (nreverse menu))))
6322
6323 (defun idlwave-split-menu-emacs (menu N)
6324   "Split the MENU into submenus of maximum length N."
6325   (if (<= (length (nth 1 menu)) (1+ N))
6326       ;; No splitting needed
6327       menu
6328     (let* ((title (car menu))
6329            (entries (cdr (nth 1 menu)))
6330            (menu nil)
6331            (cnt 0)
6332            (nextmenu nil))
6333       (while entries
6334         (while (and entries (< cnt N))
6335           (setq cnt (1+ cnt)
6336                 nextmenu (cons (car entries) nextmenu)
6337                 entries (cdr entries)))
6338         (setq nextmenu (nreverse nextmenu))
6339         (prin1 nextmenu)
6340         (setq nextmenu (cons (format "%s...%s"
6341                                      (car (car nextmenu))
6342                                      (car (nth (1- cnt) nextmenu)))
6343                              nextmenu))
6344         (setq menu (cons nextmenu menu)
6345               nextmenu nil
6346               cnt 0))
6347       (setq menu (nreverse menu))
6348       (setq menu (cons title menu))
6349       menu)))
6350
6351 (defvar idlwave-completion-setup-hook nil)
6352
6353 (defun idlwave-scroll-completions (&optional message)
6354   "Scroll the completion window on this frame."
6355   (let ((cwin (get-buffer-window "*Completions*" 'visible))
6356         (win (selected-window)))
6357     (unwind-protect
6358         (progn
6359           (select-window cwin)
6360           (condition-case nil
6361               (scroll-up)
6362             (error (if (and (listp last-command)
6363                             (nth 2 last-command))
6364                        (progn
6365                          (select-window win)
6366                          (eval idlwave-complete-after-success-form))
6367                      (set-window-start cwin (point-min)))))
6368           (and message (message message)))
6369       (select-window win))))
6370
6371 (defun idlwave-display-completion-list (list &optional message beg complete)
6372   "Display the completions in LIST in the completions buffer and echo MESSAGE."
6373   (unless (and (get-buffer-window "*Completions*")
6374                (idlwave-local-value 'idlwave-completion-p "*Completions*"))
6375     (move-marker idlwave-completion-mark beg)
6376     (setq idlwave-before-completion-wconf (current-window-configuration)))
6377
6378   (if (featurep 'xemacs)
6379       (idlwave-display-completion-list-xemacs 
6380        list)
6381     (idlwave-display-completion-list-emacs list))
6382
6383   ;; Store a special value in `this-command'.  When `idlwave-complete'
6384   ;; finds this in `last-command', it will scroll the *Completions* buffer.
6385   (setq this-command (list 'idlwave-display-completion-list message complete))
6386
6387   ;; Mark the completions buffer as created by cib
6388   (idlwave-set-local 'idlwave-completion-p t "*Completions*")
6389
6390   ;; Fontify the classes
6391   (if (and idlwave-completion-fontify-classes
6392            (consp (car list)))
6393       (idlwave-completion-fontify-classes))
6394
6395   ;; Run the hook
6396   (run-hooks 'idlwave-completion-setup-hook)
6397
6398   ;; Display the message
6399   (message (or message "Making completion list...done")))
6400
6401 (defun idlwave-choose (function &rest args)
6402   "Call FUNCTION as a completion chooser and pass ARGS to it."
6403   (let ((completion-ignore-case t))         ; install correct value
6404     (apply function args))
6405   (if (and (eq major-mode 'idlwave-shell-mode)
6406            (boundp 'font-lock-mode)
6407            (not font-lock-mode))
6408       ;; For the shell, remove the fontification of the word before point
6409       (let ((beg (save-excursion
6410                    (skip-chars-backward "a-zA-Z0-9_")
6411                    (point))))
6412         (remove-text-properties beg (point) '(face nil))))
6413   (eval idlwave-complete-after-success-form-force))
6414
6415 (defun idlwave-keyboard-quit ()
6416   (interactive)
6417   (unwind-protect
6418       (if (eq (car-safe last-command) 'idlwave-display-completion-list)
6419           (idlwave-restore-wconf-after-completion))
6420     (keyboard-quit)))
6421
6422 (defun idlwave-restore-wconf-after-completion ()
6423   "Restore the old (before completion) window configuration."
6424   (and idlwave-completion-restore-window-configuration
6425        idlwave-before-completion-wconf
6426        (set-window-configuration idlwave-before-completion-wconf)))
6427
6428 (defun idlwave-one-key-select (sym prompt delay)
6429   "Make the user select an element from the alist in the variable SYM.
6430 The keys of the alist are expected to be strings.  The function returns the
6431 car of the selected association.
6432 To do this, PROMPT is displayed and and the user must hit a letter key to
6433 select an entry.  If the user does not reply within DELAY seconds, a help
6434 window with the options is displayed automatically.
6435 The key which is associated with each option is generated automatically.
6436 First, the strings are checked for preselected keys, like in \"[P]rint\".
6437 If these don't exist, a letter in the string is automatically selected."
6438   (let* ((alist (symbol-value sym))
6439          (temp-buffer-show-hook (if (fboundp 'fit-window-to-buffer)
6440                                     '(fit-window-to-buffer)))
6441          keys-alist char)
6442     ;; First check the cache
6443     (if (and (eq (symbol-value sym) (get sym :one-key-alist-last)))
6444         (setq keys-alist (get sym :one-key-alist-cache))
6445       ;; Need to make new list
6446       (setq keys-alist (idlwave-make-one-key-alist alist))
6447       (put sym :one-key-alist-cache keys-alist)
6448       (put sym :one-key-alist-last alist))
6449     ;; Display prompt and wait for quick reply
6450     (message "%s[%s]" prompt
6451              (mapconcat (lambda(x) (char-to-string (car x)))
6452                         keys-alist ""))
6453     (if (sit-for delay)
6454         ;; No quick reply: Show help
6455         (save-window-excursion
6456           (with-output-to-temp-buffer "*Completions*"
6457             (mapcar (lambda(x)
6458                       (princ (nth 1 x))
6459                       (princ "\n"))
6460                     keys-alist))            
6461           (setq char (read-char)))
6462       (setq char (read-char)))
6463     (message nil)
6464     ;; Return the selected result
6465     (nth 2 (assoc char keys-alist))))
6466
6467 ;; Used for, e.g., electric debug super-examine.
6468 (defun idlwave-make-one-key-alist (alist)
6469   "Make an alist for single key selection."
6470   (let ((l alist) keys-alist name start char help
6471         (cnt 0)
6472         (case-fold-search nil))
6473     (while l
6474       (setq name (car (car l))
6475             l (cdr l))
6476       (catch 'exit
6477         ;; First check if the configuration predetermined a key
6478         (if (string-match "\\[\\(.\\)\\]" name)
6479             (progn
6480               (setq char (string-to-char (downcase (match-string 1 name)))
6481                     help (format "%c:  %s" char name)
6482                     keys-alist (cons (list char help name) keys-alist))
6483               (throw 'exit t)))
6484         ;; Then check for capital letters
6485         (setq start 0)
6486         (while (string-match "[A-Z]" name start)
6487           (setq start (match-end 0)
6488                 char (string-to-char (downcase (match-string 0 name))))
6489           (if (not (assoc char keys-alist))
6490               (progn
6491                 (setq help (format "%c:  %s" char
6492                                    (replace-match
6493                                     (concat "[" (match-string 0 name) "]")
6494                                           t t name))
6495                       keys-alist (cons (list char help name) keys-alist))
6496                 (throw 'exit t))))
6497         ;; Now check for lowercase letters
6498         (setq start 0)
6499         (while (string-match "[a-z]" name start)
6500           (setq start (match-end 0)
6501                 char (string-to-char (match-string 0 name)))
6502           (if (not (assoc char keys-alist))
6503               (progn
6504                 (setq help (format "%c:  %s" char
6505                                    (replace-match
6506                                     (concat "[" (match-string 0 name) "]")
6507                                     t t name))
6508                       keys-alist (cons (list char help name) keys-alist))
6509                 (throw 'exit t))))
6510         ;; Bummer, nothing found!  Use a stupid number
6511         (setq char (string-to-char (int-to-string (setq cnt (1+ cnt))))
6512               help (format "%c:  %s" char name)
6513               keys-alist (cons (list char help name) keys-alist))))
6514     (nreverse keys-alist)))
6515
6516 (defun idlwave-set-local (var value &optional buffer)
6517   "Set the buffer-local value of VAR in BUFFER to VALUE."
6518   (save-excursion
6519     (set-buffer (or buffer (current-buffer)))
6520     (set (make-local-variable var) value)))
6521
6522 (defun idlwave-local-value (var &optional buffer)
6523   "Return the value of VAR in BUFFER, but only if VAR is local to BUFFER."
6524   (save-excursion
6525     (set-buffer (or buffer (current-buffer)))
6526     (and (local-variable-p var (current-buffer))
6527          (symbol-value var))))
6528
6529 ;; In XEmacs, we can use :activate-callback directly to advice the
6530 ;; choose functions.  We use the private keymap only for the online
6531 ;; help feature.
6532
6533 (defvar idlwave-completion-map nil
6534   "Keymap for completion-list-mode with idlwave-complete.")
6535
6536 (defun idlwave-display-completion-list-xemacs (list &rest cl-args)
6537   (with-output-to-temp-buffer "*Completions*"
6538     (apply 'display-completion-list list
6539            ':activate-callback 'idlwave-default-choose-completion
6540            cl-args))
6541   (save-excursion
6542     (set-buffer "*Completions*")
6543     (use-local-map
6544      (or idlwave-completion-map
6545          (setq idlwave-completion-map
6546                (idlwave-make-modified-completion-map-xemacs
6547                 (current-local-map)))))))
6548
6549 (defun idlwave-default-choose-completion (&rest args)
6550   "Execute `default-choose-completion' and then restore the win-conf."
6551   (apply 'idlwave-choose 'default-choose-completion args))
6552
6553 (defun idlwave-make-modified-completion-map-xemacs (old-map)
6554   "Replace `choose-completion' and `mouse-choose-completion' in OLD-MAP."
6555   (let ((new-map (copy-keymap old-map)))
6556     (define-key new-map [button3up] 'idlwave-mouse-completion-help)
6557     (define-key new-map [button3] (lambda ()
6558                                     (interactive)
6559                                     (setq this-command last-command)))
6560     new-map))
6561
6562 ;; In Emacs we also replace keybindings in the completion
6563 ;; map in order to install our wrappers.
6564
6565 (defun idlwave-display-completion-list-emacs (list)
6566   "Display completion list and install the choose wrappers."
6567   (with-output-to-temp-buffer "*Completions*"
6568     (display-completion-list list))
6569   (save-excursion
6570     (set-buffer "*Completions*")
6571     (use-local-map
6572      (or idlwave-completion-map
6573          (setq idlwave-completion-map
6574                (idlwave-make-modified-completion-map-emacs
6575                 (current-local-map)))))))
6576
6577 (defun idlwave-make-modified-completion-map-emacs (old-map)
6578   "Replace `choose-completion' and `mouse-choose-completion' in OLD-MAP."
6579   (let ((new-map (copy-keymap old-map)))
6580     (substitute-key-definition 
6581      'choose-completion 'idlwave-choose-completion new-map)
6582     (substitute-key-definition
6583      'mouse-choose-completion 'idlwave-mouse-choose-completion new-map)
6584     (define-key new-map [mouse-3] 'idlwave-mouse-completion-help)
6585     new-map))
6586
6587 (defun idlwave-choose-completion (&rest args)
6588   "Choose the completion that point is in or next to."
6589   (interactive)
6590   (apply 'idlwave-choose 'choose-completion args))
6591
6592 (defun idlwave-mouse-choose-completion (&rest args)
6593   "Click on an alternative in the `*Completions*' buffer to choose it."
6594   (interactive "e")
6595   (apply 'idlwave-choose 'mouse-choose-completion args))
6596
6597 ;;----------------------------------------------------------------------
6598 ;;----------------------------------------------------------------------
6599
6600 ;;; ------------------------------------------------------------------------
6601 ;;; Stucture parsing code, and code to manage class info
6602
6603 ;;
6604 ;; - Go again over the documentation how to write a completion
6605 ;;   plugin.  It is in self.el, but currently still very bad.
6606 ;;   This could be in a separate file in the distribution, or 
6607 ;;   in an appendix for the manual.  
6608
6609 (defvar idlwave-struct-skip
6610   "[ \t]*\\(\\$.*\n\\(^[ \t]*\\(\\$[ \t]*\\)?\\(;.*\\)?\n\\)*\\)?[ \t]*"
6611   "Regexp for skipping continued blank or comment-only lines in
6612 structures")
6613
6614 (defun idlwave-struct-tags ()
6615   "Return a list of all tags in the structure defined at point.
6616 Point is expected just before the opening `{' of the struct definition."
6617   (save-excursion
6618     (let* ((borders (idlwave-struct-borders))
6619            (beg (car borders))
6620            (end (cdr borders))
6621            tags)
6622       (goto-char beg)
6623       (while (re-search-forward 
6624               (concat "[{,]" ;leading comma/brace
6625                       idlwave-struct-skip ; 4 groups
6626                       "\\([a-zA-Z][a-zA-Z0-9_]*\\)" ;the tag itself, group 5
6627                       "[ \t]*:")   ; the final colon
6628               end t)
6629         ;; Check if we are still on the top level of the structure.
6630         (if (and (condition-case nil (progn (up-list -1) t) (error nil))
6631                  (= (point) beg))
6632             (push (match-string-no-properties 5) tags))
6633         (goto-char (match-end 0)))
6634       (nreverse tags))))
6635
6636 (defun idlwave-find-struct-tag (tag)
6637   "Find a given TAG in the structure defined at point."
6638   (let* ((borders (idlwave-struct-borders))
6639          (beg (car borders))
6640          (end (cdr borders))
6641          (case-fold-search t))
6642     (re-search-forward (concat "\\(^[ \t]*\\|[,{][ \t]*\\)" tag "[ \t]*:") 
6643                        end t)))
6644
6645 (defun idlwave-struct-inherits ()
6646   "Return a list of all `inherits' names in the struct at point.
6647 Point is expected just before the opening `{' of the struct definition."
6648   (save-excursion
6649     (let* ((borders (idlwave-struct-borders))
6650            (beg (car borders))
6651            (end (cdr borders))
6652            (case-fold-search t)
6653            names)
6654       (goto-char beg)
6655       (while (re-search-forward 
6656               (concat "[{,]"  ;leading comma/brace
6657                       idlwave-struct-skip ; 4 groups
6658                       "inherits"    ; The INHERITS tag
6659                       idlwave-struct-skip ; 4 more
6660                       "\\([a-zA-Z][a-zA-Z0-9_]*\\)") ; The super-group, #9
6661               end t)
6662         ;; Check if we are still on the top level of the structure.
6663         (if (and (condition-case nil (progn (up-list -1) t) (error nil))
6664                  (= (point) beg))
6665             (push (match-string-no-properties 9) names))
6666         (goto-char (match-end 0)))
6667       (nreverse names))))
6668
6669 (defun idlwave-in-structure ()
6670   "Return t if point is inside an IDL structure."
6671   (let ((beg (point)))
6672     (save-excursion
6673       (if (not (or (idlwave-in-comment) (idlwave-in-quote)))
6674           (if (idlwave-find-structure-definition nil nil 'back)
6675               (let ((borders (idlwave-struct-borders)))
6676                 (or (= (car borders) (cdr borders)) ;; struct not yet closed...
6677                     (and (> beg (car borders)) (< beg (cdr borders))))))))))
6678
6679 (defun idlwave-struct-borders ()
6680   "Return the borders of the {...} after point as a cons cell."
6681   (let (beg)
6682     (save-excursion
6683       (skip-chars-forward "^{")
6684       (setq beg (point))
6685       (condition-case nil (forward-list 1)
6686         (error (goto-char beg)))
6687       (cons beg (point)))))
6688
6689 (defun idlwave-find-structure-definition (&optional var name bound)
6690   "Search forward for a structure definition.  
6691 If VAR is non-nil, search for a structure assigned to variable VAR.
6692 If NAME is non-nil, search for a named structure NAME.  If BOUND is an
6693 integer, limit the search.  If BOUND is the symbol `all', we search
6694 first back and then forward through the entire file.  If BOUND is the
6695 symbol `back' we search only backward."
6696   (let* ((ws "[ \t]*\\(\\$.*\n[ \t]*\\)*")
6697          (case-fold-search t)
6698          (lim (if (integerp bound) bound nil))
6699          (re (concat
6700               (if var
6701                   (concat "\\<" (regexp-quote (downcase var)) "\\>" ws)
6702                 "\\(\\)")
6703               "=" ws "\\({\\)"
6704               (if name (concat ws "\\<" (downcase name) "[^a-zA-Z0-9_$]") ""))))
6705     (if (or (and (or (eq bound 'all) (eq bound 'back))
6706                  (re-search-backward re nil t))
6707             (and (not (eq bound 'back)) (re-search-forward re lim t)))
6708         (goto-char (match-beginning 3)))))
6709
6710 (defvar idlwave-class-info nil)
6711 (defvar idlwave-system-class-info nil)
6712 (add-hook 'idlwave-update-rinfo-hook
6713           (lambda () (setq idlwave-class-info nil)))
6714 (add-hook 'idlwave-after-load-rinfo-hook
6715           (lambda () (setq idlwave-class-info nil)))
6716
6717 (defun idlwave-class-info (class)
6718   (let (list entry)
6719     (unless idlwave-class-info
6720       ;; Info is nil, put in the system stuff.
6721       (setq idlwave-class-info idlwave-system-class-info)
6722       (setq list idlwave-class-info)
6723       (while (setq entry (pop list))
6724         (idlwave-sintern-class-info entry)))
6725     (setq class (idlwave-sintern-class class))
6726     (setq entry (assq class idlwave-class-info))
6727     (unless entry  ;; Find the __define file, parse and include it
6728       (setq entry (idlwave-find-class-info class))
6729       (when entry
6730         ;; Sintern and cache the info
6731         (idlwave-sintern-class-info entry)
6732         (push entry idlwave-class-info)))
6733     entry))
6734
6735 (defun idlwave-sintern-class-info (entry)
6736   "Sintern the class names in a class-info entry."
6737   (let ((taglist (assq 'tags entry))
6738         (inherits (assq 'inherits entry)))
6739     (setcar entry (idlwave-sintern-class (car entry) 'set))
6740     (if inherits
6741         (setcdr inherits (mapcar (lambda (x) (idlwave-sintern-class x 'set))
6742                                  (cdr inherits))))))
6743
6744 (defun idlwave-find-class-definition (class)
6745   (let ((case-fold-search t))
6746     (if (re-search-forward
6747          (concat "^[ \t]*pro[ \t]+" (downcase class) "__define" "\\>") nil t)
6748         ;; FIXME: should we limit to end of pro here?
6749         (idlwave-find-structure-definition nil class))))
6750
6751 (defun idlwave-find-class-info (class)
6752   "Find the __define procedure for a class structure and return info entry."
6753   (let* ((pro (concat (downcase class) "__define"))
6754          (class (idlwave-sintern-class class))
6755          (idlwave-auto-routine-info-updates nil)
6756          (file (idlwave-routine-source-file
6757                 (nth 3 (idlwave-rinfo-assoc pro 'pro nil
6758                                             (idlwave-routines)))))
6759          buf)
6760     (if (or (not file)
6761             (not (file-regular-p file)))
6762         nil ; Cannot get info
6763       (save-excursion
6764         (if (setq buf (idlwave-get-buffer-visiting file))
6765             (set-buffer buf)
6766           (set-buffer (get-buffer-create " *IDLWAVE-tmp*"))
6767           (erase-buffer)
6768           (unless (eq major-mode 'idlwave-mode)
6769             (idlwave-mode))
6770           (insert-file-contents file))
6771         (save-excursion
6772           (goto-char 1)
6773           (if (idlwave-find-class-definition class)
6774               (list class
6775                     (cons 'tags (idlwave-struct-tags))
6776                     (cons 'inherits (idlwave-struct-inherits)))))))))
6777
6778 (defun idlwave-class-tags (class)
6779   "Return the native tags in CLASS."
6780   (cdr (assq 'tags (idlwave-class-info class))))
6781 (defun idlwave-class-inherits (class)
6782   "Return the direct superclasses of CLASS."
6783   (cdr (assq 'inherits (idlwave-class-info class))))
6784 (defun idlwave-class-file (class)
6785   "Return the HTML help file (if any) for CLASS."
6786   (cdr (assq 'file (idlwave-class-info class))))
6787
6788 (defun idlwave-all-class-tags (class)
6789   "Return a list of native and inherited tags in CLASS."
6790   (condition-case err
6791       (apply 'append (mapcar 'idlwave-class-tags
6792                              (cons class (idlwave-all-class-inherits class))))
6793     (error           
6794      (idlwave-class-tag-reset)
6795      (error "%s" (error-message-string err)))))
6796
6797
6798 (defun idlwave-all-class-inherits (class)
6799   "Return a list of all superclasses of CLASS (recursively expanded).
6800 The list is cached in `idlwave-class-info' for faster access."
6801   (cond
6802    ((not idlwave-support-inheritance) nil)
6803    ((eq class nil) nil)
6804    ((eq class t) nil)
6805    (t
6806     (let ((info (idlwave-class-info class))
6807           entry)
6808       (if (setq entry (assq 'all-inherits info))
6809           (cdr entry)
6810         ;; Save the depth of inheritance scan to check for circular references
6811         (let ((inherits (mapcar (lambda (x) (cons x 0))
6812                                 (idlwave-class-inherits class)))
6813               rtn all-inherits cl)
6814           (while inherits
6815             (setq cl (pop inherits)
6816                   rtn (cons (car cl) rtn)
6817                   inherits (append (mapcar (lambda (x)
6818                                              (cons x (1+ (cdr cl))))
6819                                            (idlwave-class-inherits (car cl)))
6820                                    inherits))
6821             (if (> (cdr cl) 999)
6822               (error
6823                "Class scan: inheritance depth exceeded. Circular inheritance?")
6824               ))
6825           (setq all-inherits (nreverse rtn))
6826           (nconc info (list (cons 'all-inherits all-inherits)))
6827           all-inherits))))))
6828
6829 (defun idlwave-entry-keywords (entry &optional record-link)
6830   "Return the flat entry keywords alist from routine-info entry.  
6831 If RECORD-LINK is non-nil, the keyword text is copies and a text
6832 property indicating the link is added."
6833   (let (kwds)
6834     (mapcar
6835      (lambda (key-list) 
6836        (let ((file (car key-list)))
6837          (mapcar (lambda (key-cons)
6838                    (let ((key (car key-cons))
6839                          (link (cdr key-cons)))
6840                      (when (and record-link file)
6841                          (setq key (copy-sequence key))
6842                          (put-text-property 
6843                           0 (length key)
6844                           'link 
6845                           (concat 
6846                            file 
6847                            (if link 
6848                                (concat "#" (number-to-string link))))
6849                           key))
6850                      (push (list key) kwds)))
6851                  (cdr key-list))))
6852      (nthcdr 5 entry))
6853     (nreverse kwds)))
6854
6855 (defun idlwave-entry-find-keyword (entry keyword)
6856   "Find keyword KEYWORD in entry ENTRY, and return (with link) if set"
6857   (catch 'exit
6858     (mapc
6859      (lambda (key-list) 
6860        (let ((file (car key-list))
6861              (kwd (assoc keyword (cdr key-list))))
6862          (when kwd
6863            (setq kwd (copy-list kwd))
6864            (if (and file (cdr kwd))
6865                (setcdr kwd (concat file "#" (number-to-string (cdr kwd)))))
6866            (throw 'exit kwd))))
6867      (nthcdr 5 entry))))
6868
6869 ;;==========================================================================
6870 ;;
6871 ;; Completing class structure tags.  This is a completion plugin.
6872 ;; The necessary taglist is constructed dynamically
6873
6874 (defvar idlwave-current-tags-class nil)
6875 (defvar idlwave-current-class-tags nil)
6876 (defvar idlwave-current-native-class-tags nil)
6877 (defvar idlwave-sint-class-tags nil)
6878 (idlwave-new-sintern-type 'class-tag)
6879 (add-to-list 'idlwave-complete-special 'idlwave-complete-class-structure-tag)
6880 (add-hook 'idlwave-update-rinfo-hook 'idlwave-class-tag-reset)
6881
6882 (defun idlwave-complete-class-structure-tag ()
6883   "Complete a structure tag on a `self' argument in an object method."
6884   (interactive)
6885   (let ((pos (point))
6886         (case-fold-search t))
6887     (if (save-excursion
6888           ;; Check if the context is right
6889           (skip-chars-backward "a-zA-Z0-9._$")
6890           (and (< (point) (- pos 4))
6891                (looking-at "self\\.")))
6892         (let* ((class-selector (nth 2 (idlwave-current-routine)))
6893                (super-classes (idlwave-all-class-inherits class-selector)))
6894           ;; Check if we are in a class routine
6895           (unless class-selector
6896             (error "Not in a method procedure or function"))
6897           ;; Check if we need to update the "current" class
6898           (if (not (equal class-selector idlwave-current-tags-class))
6899               (idlwave-prepare-class-tag-completion class-selector))
6900           (setq idlwave-completion-help-info 
6901                 (list 'idlwave-complete-class-structure-tag-help
6902                       (idlwave-sintern-routine 
6903                        (concat class-selector "__define"))
6904                       nil))
6905           (let  ((idlwave-cpl-bold idlwave-current-native-class-tags))
6906             (idlwave-complete-in-buffer
6907              'class-tag 'class-tag 
6908              idlwave-current-class-tags nil
6909              (format "Select a tag of class %s" class-selector)
6910              "class tag"
6911              'idlwave-attach-class-tag-classes))
6912           t) ; return t to skip other completions
6913       nil)))
6914
6915 (defun idlwave-class-tag-reset ()
6916   (setq idlwave-current-tags-class nil))
6917
6918 (defun idlwave-prepare-class-tag-completion (class)
6919   "Find and parse the necessary class definitions for class structure tags."
6920   (setq idlwave-sint-class-tags nil)
6921   (setq idlwave-current-tags-class class)
6922   (setq idlwave-current-class-tags
6923         (mapcar (lambda (x)
6924                   (list (idlwave-sintern-class-tag x 'set)))
6925                 (idlwave-all-class-tags class)))
6926   (setq idlwave-current-native-class-tags
6927         (mapcar 'downcase (idlwave-class-tags class))))
6928
6929 ;===========================================================================
6930 ;;
6931 ;; Completing system variables and their structure fields
6932 ;; This is also a plugin.
6933
6934 (defvar idlwave-sint-sysvars nil)
6935 (defvar idlwave-sint-sysvartags nil)
6936 (idlwave-new-sintern-type 'sysvar)
6937 (idlwave-new-sintern-type 'sysvartag)
6938 (add-to-list 'idlwave-complete-special 'idlwave-complete-sysvar-or-tag)
6939 (add-hook 'idlwave-update-rinfo-hook 'idlwave-sysvars-reset)
6940 (add-hook 'idlwave-after-load-rinfo-hook 'idlwave-sintern-sysvar-alist)
6941
6942 (defvar idlwave-executive-commands-alist nil
6943   "Alist of system variables and their help files.")
6944
6945 (defvar idlwave-system-variables-alist nil
6946   "Alist of system variables and the associated structure tags.
6947 Gets set in `idlw-rinfo.el'.")
6948
6949 (defun idlwave-complete-sysvar-or-tag ()
6950   "Complete a system variable."
6951   (interactive)
6952   (let ((pos (point))
6953         (case-fold-search t))
6954     (cond ((save-excursion
6955              ;; Check if the context is right for system variable
6956              (skip-chars-backward "[a-zA-Z0-9_$]")
6957              (equal (char-before) ?!))
6958            (setq idlwave-completion-help-info '(idlwave-complete-sysvar-help))
6959            (idlwave-complete-in-buffer 'sysvar 'sysvar 
6960                                        idlwave-system-variables-alist nil
6961                                        "Select a system variable"
6962                                        "system variable")
6963            t)  ; return t to skip other completions
6964           ((save-excursion
6965              ;; Check if the context is right for sysvar tag
6966              (skip-chars-backward "a-zA-Z0-9_$.")
6967              (and (equal (char-before) ?!)
6968                   (looking-at "\\([a-zA-Z][a-zA-Z0-9_$]*\\)\\.")
6969                   (<= (match-end 0) pos)))
6970            ;; Complete a system variable tag
6971            (let* ((var (idlwave-sintern-sysvar (match-string 1)))
6972                   (entry (assq var idlwave-system-variables-alist))
6973                   (tags (cdr (assq 'tags entry))))
6974              (or entry (error "!%s is not a known system variable" var))
6975              (or tags (error "System variable !%s is not a structure" var))
6976              (setq idlwave-completion-help-info
6977                    (list 'idlwave-complete-sysvar-tag-help var))
6978              (idlwave-complete-in-buffer 'sysvartag 'sysvartag 
6979                                          tags nil
6980                                          "Select a system variable tag"
6981                                          "system variable tag")
6982              t)) ; return t to skip other completions
6983           (t nil))))
6984
6985 ;; Here we fake help using the routine "system variables" with keyword
6986 ;; set to the sysvar.  Name and kwd are global variables here.
6987 (defvar name) 
6988 (defvar kwd)
6989
6990 ;; Get rid of opaque dynamic variable passing of link?
6991 (defun idlwave-complete-sysvar-help (mode word)
6992   (let ((word (or (nth 1 idlwave-completion-help-info) word))
6993         (entry (assoc word idlwave-system-variables-alist)))
6994     (cond
6995      ((eq mode 'test)
6996       (and (stringp word) entry (nth 1 (assq 'link entry))))
6997      ((eq mode 'set)
6998       (if entry (setq link (nth 1 (assq 'link entry))))) ;; setting dynamic!!!
6999      (t (error "This should not happen")))))
7000
7001 (defun idlwave-complete-sysvar-tag-help (mode word)
7002   (let* ((var (nth 1 idlwave-completion-help-info))
7003         (entry (assoc var idlwave-system-variables-alist))
7004         (tags (cdr (assq 'tags entry)))
7005         (main (nth 1 (assq 'link entry)))
7006         target main-base)
7007     (cond
7008      ((eq mode 'test) ; we can at least link the main
7009       (and (stringp word) entry main))
7010      ((eq mode 'set)
7011       (if entry 
7012           (setq link 
7013                 (if (setq target (cdr (assoc word tags)))
7014                   (idlwave-substitute-link-target main target)
7015                 main)))) ;; setting dynamic!!!
7016      (t (error "This should not happen")))))
7017
7018 (defun idlwave-substitute-link-target (link target)
7019   "Substitute the target anchor for the given link."
7020   (let (main-base)
7021     (setq main-base (if (string-match "#" link)
7022                         (substring link 0 (match-beginning 0))
7023                       link))
7024     (if target
7025         (concat main-base "#" (number-to-string target))
7026       link)))
7027
7028 ;; Fake help in the source buffer for class structure tags.
7029 ;; kwd and name are global-variables here.
7030 (defvar idlwave-help-do-class-struct-tag nil)
7031 (defun idlwave-complete-class-structure-tag-help (mode word)
7032   (cond
7033    ((eq mode 'test) ; nothing gets fontified for class tags
7034     nil)
7035    ((eq mode 'set)
7036     (let (class-with)
7037       (when (setq class-with 
7038                 (idlwave-class-or-superclass-with-tag 
7039                  idlwave-current-tags-class
7040                  word))
7041         (if (assq (idlwave-sintern-class class-with) 
7042                   idlwave-system-class-info)
7043             (error "No help available for system class tags."))
7044         (setq name (concat class-with "__define"))))
7045     (setq kwd word
7046           idlwave-help-do-class-struct-tag t))
7047    (t (error "This should not happen"))))
7048
7049 (defun idlwave-class-or-superclass-with-tag (class tag)
7050   "Find and return the CLASS or one of its superclass with the
7051 associated TAG, if any."
7052   (let ((sclasses (cons class (cdr (assq 'all-inherits 
7053                                          (idlwave-class-info class)))))
7054         cl)
7055    (catch 'exit
7056      (while sclasses
7057        (setq cl (pop sclasses))
7058        (let ((tags (idlwave-class-tags cl)))
7059          (while tags
7060            (if (eq t (compare-strings tag 0 nil (car tags) 0 nil t))
7061              (throw 'exit cl))         
7062            (setq tags (cdr tags))))))))
7063
7064
7065 (defun idlwave-sysvars-reset ()
7066   (if (and (fboundp 'idlwave-shell-is-running)
7067            (idlwave-shell-is-running)
7068            idlwave-idlwave_routine_info-compiled)
7069       (idlwave-shell-send-command "idlwave_get_sysvars"
7070                                   'idlwave-process-sysvars 'hide)))
7071
7072 (defun idlwave-process-sysvars ()
7073   (idlwave-shell-filter-sysvars)
7074   (setq idlwave-sint-sysvars nil
7075         idlwave-sint-sysvartags nil)
7076   (idlwave-sintern-sysvar-alist))
7077
7078 (defun idlwave-sintern-sysvar-alist ()
7079   (let ((list idlwave-system-variables-alist) entry tags)
7080     (while (setq entry (pop list))
7081       (setcar entry (idlwave-sintern-sysvar (car entry) 'set))
7082       (setq tags (assq 'tags entry))
7083       (if tags
7084           (setcdr tags 
7085                   (mapcar (lambda (x) 
7086                             (cons (idlwave-sintern-sysvartag (car x) 'set)
7087                                   (cdr x)))
7088                           (cdr tags)))))))
7089
7090 (defvar idlwave-shell-command-output)
7091 (defun idlwave-shell-filter-sysvars ()
7092   "Get any new system variables and tags."
7093   (let ((text idlwave-shell-command-output)
7094         (start 0)
7095         (old idlwave-system-variables-alist)
7096         var tags type name class link old-entry)
7097     (setq idlwave-system-variables-alist nil)
7098     (while (string-match "^IDLWAVE-SYSVAR: !\\([a-zA-Z0-9_$]+\\)\\( \\(.*\\)\\)?"
7099                          text start)
7100       (setq start (match-end 0)
7101             var (match-string 1 text)
7102             tags (if (match-end 3) 
7103                      (idlwave-split-string (match-string 3 text))))
7104       ;; Maintain old links, if present
7105       (setq old-entry (assq (idlwave-sintern-sysvar var) old))
7106       (setq link (assq 'link old-entry))
7107       (setq idlwave-system-variables-alist
7108             (cons (list var 
7109                         (cons 
7110                          'tags 
7111                          (mapcar (lambda (x) 
7112                                    (cons x 
7113                                          (cdr (assq 
7114                                                (idlwave-sintern-sysvartag x) 
7115                                                (cdr (assq 'tags old-entry))))))
7116                                  tags)) link)
7117                   idlwave-system-variables-alist)))
7118     ;; Keep the old value if query was not successful
7119     (setq idlwave-system-variables-alist
7120           (or idlwave-system-variables-alist old))))
7121
7122 (defun idlwave-completion-fontify-classes ()
7123   "Goto the *Completions* buffer and fontify the class info."
7124   (when (featurep 'font-lock)
7125     (save-excursion
7126       (set-buffer "*Completions*")
7127       (save-excursion
7128         (goto-char (point-min))
7129         (let ((buffer-read-only nil))
7130           (while (re-search-forward "\\.*<[^>]+>" nil t)
7131             (put-text-property (match-beginning 0) (match-end 0)
7132                                'face 'font-lock-string-face)))))))
7133
7134 (defun idlwave-uniquify (list)
7135   (let ((ht (make-hash-table :size (length list) :test 'equal)))
7136     (delq nil 
7137           (mapcar (lambda (x)
7138                     (unless (gethash x ht) 
7139                       (puthash x t ht)
7140                       x))
7141                   list))))
7142
7143 (defun idlwave-after-successful-completion (type slash &optional verify)
7144   "Add `=' or `(' after successful completion of keyword and function.
7145 Restore the pre-completion window configuration if possible."
7146   (cond
7147    ((eq type 'procedure)
7148     nil)
7149    ((eq type 'function)
7150     (cond
7151      ((equal idlwave-function-completion-adds-paren nil) nil)
7152      ((or (equal idlwave-function-completion-adds-paren t)
7153           (equal idlwave-function-completion-adds-paren 1))
7154       (insert "("))
7155      ((equal idlwave-function-completion-adds-paren 2)
7156       (insert "()")
7157       (backward-char 1))
7158      (t nil)))
7159    ((eq type 'keyword)
7160     (if (and idlwave-keyword-completion-adds-equal
7161              (not slash))
7162         (progn (insert "=") t)
7163       nil)))
7164
7165   ;; Restore the pre-completion window configuration if this is safe.
7166   
7167   (if (or (eq verify 'force)                                    ; force 
7168           (and 
7169            (get-buffer-window "*Completions*")                  ; visible
7170            (idlwave-local-value 'idlwave-completion-p 
7171                                 "*Completions*")                ; cib-buffer
7172            (eq (marker-buffer idlwave-completion-mark)
7173                (current-buffer))                                ; buffer OK
7174            (equal (marker-position idlwave-completion-mark)
7175                   verify)))                                     ; pos OK
7176       (idlwave-restore-wconf-after-completion))
7177   (move-marker idlwave-completion-mark nil)
7178   (setq idlwave-before-completion-wconf nil))
7179
7180 (defun idlwave-mouse-context-help (ev &optional arg)
7181   "Call `idlwave-context-help' on the clicked location."
7182   (interactive "eP")
7183   (mouse-set-point ev)
7184   (idlwave-context-help arg))
7185
7186 (defvar idlwave-last-context-help-pos nil)
7187 (defun idlwave-context-help (&optional arg)
7188   "Display IDL Online Help on context.
7189 If point is on a keyword, help for that keyword will be shown.  If
7190 point is on a routine name or in the argument list of a routine, help
7191 for that routine will be displayed.  Works for system routines and
7192 keywords, it pulls up text help.  For other routies and keywords,
7193 visits the source file, finding help in the header (if
7194 `idlwave-help-source-try-header' is non-nil) or the routine definition
7195 itself."
7196   (interactive "P")
7197   (idlwave-do-context-help arg))
7198
7199 (defun idlwave-mouse-completion-help (ev)
7200   "Display online help about the completion at point."
7201   (interactive "eP")
7202   ;; Restore last-command for next command, to make
7203   ;; scrolling/cancelling of completions work.
7204   (setq this-command last-command)
7205   (idlwave-do-mouse-completion-help ev))
7206
7207 (defun idlwave-routine-info (&optional arg external)
7208   "Display a routines calling sequence and list of keywords.  When
7209 point is on the name a function or procedure, or in the argument list
7210 of a function or procedure, this command displays a help buffer with
7211 the information.  When called with prefix arg, enforce class query.
7212
7213 When point is on an object operator `->', display the class stored in
7214 this arrow, if any (see `idlwave-store-inquired-class').  With a
7215 prefix arg, the class property is cleared out."
7216
7217   (interactive "P")
7218   (idlwave-routines)
7219   (if (string-match "->" (buffer-substring
7220                           (max (point-min) (1- (point)))
7221                           (min (+ 2 (point)) (point-max))))
7222       ;; Cursor is on an arrow
7223       (if (get-text-property (point) 'idlwave-class)
7224           ;; arrow has class property
7225           (if arg
7226               ;; Remove property
7227               (save-excursion
7228                 (backward-char 1)
7229                 (when (looking-at ".?\\(->\\)")
7230                   (remove-text-properties (match-beginning 1) (match-end 1)
7231                                           '(idlwave-class nil face nil))
7232                   (message "Class property removed from arrow")))
7233             ;; Echo class property
7234             (message "Arrow has text property identifying object to be class %s"
7235                      (get-text-property (point) 'idlwave-class)))
7236         ;; No property found
7237         (message "Arrow has no class text property"))
7238
7239     ;; Not on an arrow...
7240     (let* ((idlwave-query-class nil)
7241            (idlwave-force-class-query (equal arg '(4)))
7242            (module (idlwave-what-module)))
7243       (if (car module)
7244           (apply 'idlwave-display-calling-sequence
7245                  (idlwave-fix-module-if-obj_new module))
7246         (error "Don't know which calling sequence to show")))))
7247
7248 (defun idlwave-resolve (&optional arg)
7249   "Call RESOLVE_ROUTINE on the module name at point.
7250 Like `idlwave-routine-info', this looks for a routine call at point.
7251 After confirmation in the minibuffer, it will use the shell to issue
7252 a RESOLVE call for this routine, to attempt to make it defined and its
7253 routine info available for IDLWAVE.  If the routine is a method call,
7254 both `class__method' and `class__define' will be tried.
7255 With ARG, enforce query for the class of object methods."
7256   (interactive "P")
7257   (let* ((idlwave-query-class nil)
7258          (idlwave-force-class-query (equal arg '(4)))
7259          (module (idlwave-what-module))
7260          (name (idlwave-make-full-name (nth 2 module) (car module)))
7261          (type (if (eq (nth 1 module) 'pro) "pro" "function"))
7262          (resolve (read-string "Resolve: " (format "%s %s" type name)))
7263          (kwd "")
7264          class)
7265     (if (string-match "\\(pro\\|function\\)[ \t]+\\(\\(.*\\)::\\)?\\(.*\\)"
7266                       resolve)
7267         (setq type (match-string 1 resolve)
7268               class (if (match-beginning 2) 
7269                         (match-string 3 resolve)
7270                       nil)
7271               name (match-string 4 resolve)))
7272     (if (string= (downcase type) "function")
7273         (setq kwd ",/is_function"))
7274
7275     (cond
7276      ((null class)
7277       (idlwave-shell-send-command 
7278        (format "resolve_routine,'%s'%s" (downcase name) kwd)
7279        'idlwave-update-routine-info
7280        nil t))
7281      (t
7282       (idlwave-shell-send-command 
7283        (format "resolve_routine,'%s__define'%s" (downcase class) kwd)
7284        (list 'idlwave-shell-send-command 
7285              (format "resolve_routine,'%s__%s'%s" 
7286                      (downcase class) (downcase name) kwd)
7287              '(idlwave-update-routine-info)
7288              nil t))))))
7289
7290 (defun idlwave-find-module (&optional arg)
7291   "Find the source code of an IDL module.
7292 Works for modules for which IDLWAVE has routine info available.
7293 The function offers as default the module name `idlwave-routine-info' would
7294 use.  With ARG force class query for object methods."
7295   (interactive "P")
7296   (let* ((idlwave-query-class nil)
7297          (idlwave-force-class-query (equal arg '(4)))
7298          (module (idlwave-fix-module-if-obj_new (idlwave-what-module)))
7299          (default (concat (idlwave-make-full-name (nth 2 module) (car module))
7300                           (if (eq (nth 1 module) 'pro) "<p>" "<f>")))
7301          (list 
7302           (idlwave-uniquify
7303            (delq nil
7304                  (mapcar (lambda (x) 
7305                            (if (eq 'system (car-safe (nth 3 x)))
7306                                ;; Take out system routines with no source.
7307                                nil
7308                              (list
7309                               (concat (idlwave-make-full-name 
7310                                        (nth 2 x) (car x))
7311                                       (if (eq (nth 1 x) 'pro) "<p>" "<f>")))))
7312                          (idlwave-routines)))))
7313          (name (idlwave-completing-read
7314                 (format "Module (Default %s): " 
7315                         (if default default "none"))
7316                 list))
7317          type class)
7318     (if (string-match "\\`\\s-*\\'" name)
7319         ;; Nothing, use the default.
7320         (setq name default))
7321     (if (string-match "<[fp]>" name)
7322         (setq type (substring name -2 -1)
7323               name (substring name 0 -3)))
7324     (if (string-match "\\(.*\\)::\\(.*\\)" name)
7325         (setq class (match-string 1 name)
7326               name (match-string 2 name)))
7327     (setq name (idlwave-sintern-routine-or-method name class)
7328           class (idlwave-sintern-class class)
7329           type (cond ((equal type "f") 'fun)
7330                      ((equal type "p") 'pro)
7331                      (t t)))
7332     (idlwave-do-find-module name type class)))
7333
7334 (defun idlwave-do-find-module (name type class &optional force-source)
7335   (let ((name1 (idlwave-make-full-name class name))
7336         source buf1 entry 
7337         (buf (current-buffer))
7338         (pos (point))
7339         file name2)
7340     (setq entry (idlwave-best-rinfo-assq name type class (idlwave-routines)
7341                                          'WITH-FILE)
7342           source (or force-source (nth 3 entry))
7343           name2 (if (nth 2 entry)
7344                     (idlwave-make-full-name (nth 2 entry) name)
7345                   name1))
7346     (if source  
7347         (setq file (idlwave-routine-source-file source)))
7348     (unless file  ; Try to find it on the path.
7349       (setq file 
7350             (idlwave-expand-lib-file-name 
7351              (if class
7352                  (format "%s__define.pro" (downcase class))
7353                (format "%s.pro" (downcase name))))))
7354     (cond
7355      ((or (null name) (equal name ""))
7356       (error "Abort"))
7357      ((eq (car source) 'system)
7358       (error "Source code for system routine %s is not available" 
7359              name2))
7360      ((or (not file) (not (file-regular-p file)))
7361       (error "Source code for routine %s is not available"
7362              name2))
7363      (t
7364       (setq buf1 
7365             (idlwave-find-file-noselect file 'find))
7366       (pop-to-buffer buf1 t)
7367       (goto-char (point-max))
7368       (let ((case-fold-search t))
7369         (if (re-search-backward
7370              (concat "^[ \t]*\\<"
7371                      (cond ((eq type 'fun) "function")
7372                            ((eq type 'pro) "pro")
7373                            (t "\\(pro\\|function\\)"))
7374                      "\\>[ \t]+" 
7375                      (regexp-quote (downcase name2))
7376                      "[^a-zA-Z0-9_$]")
7377              nil t)
7378             (goto-char (match-beginning 0))
7379           (pop-to-buffer buf)
7380           (goto-char pos)
7381           (error "Could not find routine %s" name2)))))))
7382
7383 (defun idlwave-what-module ()
7384   "Return a default module for stuff near point.
7385 Used by `idlwave-routine-info' and `idlwave-find-module'."
7386   (idlwave-routines)
7387   (if (let ((case-fold-search t))
7388         (save-excursion
7389           (idlwave-beginning-of-statement)
7390           (looking-at "[ \t]*\\(pro\\|function\\)[ \t]+\\(\\([a-zA-Z0-9_$]+\\)::\\)?\\([a-zA-Z0-9$_]+\\)\\([, \t\n]\\|$\\)")))
7391       ;; This is a function or procedure definition statement
7392       ;; We return the defined routine as module.
7393       (list
7394        (idlwave-sintern-routine-or-method (match-string-no-properties 4)
7395                                           (match-string-no-properties 2))
7396        (if (equal (downcase (match-string 1)) "pro") 'pro 'fun)
7397        (idlwave-sintern-class (match-string 3)))
7398
7399     ;; Not a definition statement - analyze precise position.
7400     (let* ((where (idlwave-where))
7401            (cw (nth 2 where))
7402            (pro (car (nth 0 where)))
7403            (func (car (nth 1 where)))
7404            (this-word (idlwave-this-word "a-zA-Z0-9$_"))
7405            (next-char (save-excursion (skip-chars-forward "a-zA-Z0-9$_")
7406                                       (following-char)))
7407            )
7408       (cond
7409        ((and (eq cw 'procedure)
7410              (not (equal this-word "")))
7411         (setq this-word (idlwave-sintern-routine-or-method 
7412                          this-word (nth 2 (nth 3 where))))
7413         (list this-word 'pro
7414               (idlwave-determine-class 
7415                (cons this-word (cdr (nth 3 where)))
7416                'pro)))
7417        ((and (eq cw 'function) 
7418              (not (equal this-word ""))
7419              (or (eq next-char ?\()     ; exclude arrays, vars.
7420                  (looking-at "[a-zA-Z0-9_]*[ \t]*(")))
7421         (setq this-word (idlwave-sintern-routine-or-method 
7422                          this-word (nth 2 (nth 3 where))))
7423         (list this-word 'fun
7424               (idlwave-determine-class
7425                (cons this-word (cdr (nth 3 where)))
7426                'fun)))
7427        ((and (memq cw '(function-keyword procedure-keyword))
7428              (not (equal this-word ""))
7429              (eq next-char ?\())        ; A function!
7430         (setq this-word (idlwave-sintern-routine this-word))
7431         (list this-word 'fun nil))
7432        (func
7433         (list func 'fun (idlwave-determine-class (nth 1 where) 'fun)))
7434        (pro
7435         (list pro 'pro (idlwave-determine-class (nth 0 where) 'pro)))
7436        (t nil)))))
7437
7438 (defun idlwave-what-module-find-class ()
7439   "Call idlwave-what-module and find the inherited class if necessary."
7440   (let* ((module (idlwave-what-module))
7441          (class (nth 2 module))
7442          classes)
7443     (if (and (= (length module) 3)
7444              (stringp class))
7445         (list (car module)
7446               (nth 1 module)
7447               (apply 'idlwave-find-inherited-class module))
7448       module)))
7449
7450 (defun idlwave-find-inherited-class (name type class)
7451   "Find the class which defines TYPE NAME and is CLASS or inherited by CLASS."
7452   (let ((entry (idlwave-best-rinfo-assoc name type class (idlwave-routines))))
7453     (if entry
7454         (nth 2 entry)
7455       class)))
7456
7457 (defun idlwave-fix-module-if-obj_new (module)
7458   "Check if MODULE points to obj_new.  
7459 If yes, and if the cursor is in the keyword region, change to the
7460 appropriate Init method."
7461   (let* ((name (car module))
7462          (pos (point))
7463          (case-fold-search t)
7464          string)
7465     (if (and (stringp name)
7466              (equal (downcase name) "obj_new")
7467              (save-excursion
7468                (idlwave-beginning-of-statement)
7469                (setq string (buffer-substring (point) pos))
7470                (string-match "obj_new([^'\"]*['\"]\\([a-zA-Z0-9_]+\\)"
7471                              string)))
7472         (let ((name "Init")
7473               (class (match-string 1 string)))
7474           (setq module (list (idlwave-sintern-method "Init")
7475                              'fun
7476                              (idlwave-sintern-class class)))))
7477     module))
7478
7479 (defun idlwave-fix-keywords (name type class keywords &optional super-classes)
7480   "Update a list of keywords.
7481 Translate OBJ_NEW, adding all super-class keywords, or all keywords
7482 from all classes if class equals t."
7483   (let ((case-fold-search t))
7484
7485     ;; If this is the OBJ_NEW function, try to figure out the class and use
7486     ;; the keywords from the corresponding INIT method.
7487     (if (and (equal (upcase name) "OBJ_NEW")
7488              (or (eq major-mode 'idlwave-mode)
7489                  (eq major-mode 'idlwave-shell-mode)))
7490         (let* ((bos (save-excursion (idlwave-beginning-of-statement) (point)))
7491                (string (buffer-substring bos (point)))
7492                (case-fold-search t)
7493                class)
7494           (and (string-match "obj_new([^'\"]*['\"]\\([a-zA-Z0-9_]+\\)"
7495                              string)
7496                (setq class (idlwave-sintern-class (match-string 1 string)))
7497                (setq idlwave-current-obj_new-class class)
7498                (setq keywords 
7499                      (append keywords 
7500                              (idlwave-entry-keywords
7501                               (idlwave-rinfo-assq
7502                                (idlwave-sintern-method "INIT")
7503                                'fun
7504                                class
7505                                (idlwave-routines)) 'do-link))))))
7506     
7507     ;; If the class is `t', combine all keywords of all methods NAME
7508     (when (eq class t)
7509       (mapc (lambda (entry)
7510               (and
7511                (nth 2 entry)             ; non-nil class
7512                (eq (nth 1 entry) type)   ; correct type
7513                (setq keywords 
7514                      (append keywords 
7515                              (idlwave-entry-keywords entry 'do-link)))))
7516             (idlwave-all-assq name (idlwave-routines)))
7517       (setq keywords (idlwave-uniquify keywords)))
7518     
7519     ;; If we have inheritance, add all keywords from superclasses, if
7520     ;; the user indicated that method in `idlwave-keyword-class-inheritance'
7521     (when (and 
7522            super-classes
7523            idlwave-keyword-class-inheritance
7524            (stringp class)
7525            (or (assq (idlwave-sintern-keyword "_extra") keywords)
7526                (assq (idlwave-sintern-keyword "_ref_extra") keywords))
7527            ;; Check if one of the keyword-class regexps matches the name
7528            (let ((regexps idlwave-keyword-class-inheritance) re)
7529              (catch 'exit
7530                (while (setq re (pop regexps))
7531                  (if (string-match re name) (throw 'exit t))))))
7532
7533       (loop for entry in (idlwave-routines) do
7534             (and (nth 2 entry)                           ; non-nil class
7535                  (memq (nth 2 entry) super-classes)      ; an inherited class
7536                  (eq (nth 1 entry) type)                 ; correct type
7537                  (eq (car entry) name)                   ; correct name
7538                  (mapcar (lambda (k) (add-to-list 'keywords k))
7539                          (idlwave-entry-keywords entry 'do-link))))
7540       (setq keywords (idlwave-uniquify keywords)))
7541     
7542     ;; Return the final list
7543     keywords))
7544
7545 (defun idlwave-expand-keyword (keyword module)
7546   "Expand KEYWORD to one of the legal keyword parameters of MODULE.
7547 KEYWORD may be an exact match or an abbreviation of a keyword.
7548 If the match is exact, KEYWORD itself is returned, even if there may be other
7549 keywords of which KEYWORD is an abbreviation.  This is necessary because some
7550 system routines have keywords which are prefixes of other keywords.
7551 If KEYWORD is an abbreviation of several keywords, a list of all possible
7552 completions is returned.
7553 If the abbreviation was unique, the correct keyword is returned.
7554 If it cannot be a keyword, the function return nil.
7555 If we do not know about MODULE, just return KEYWORD literally."
7556   (let* ((name (car module))
7557          (type (nth 1 module))
7558          (class (nth 2 module))
7559          (kwd (idlwave-sintern-keyword keyword))
7560          (entry (idlwave-best-rinfo-assoc name type class (idlwave-routines)))
7561          (kwd-alist (idlwave-entry-keywords entry))
7562          (extra (or (assq (idlwave-sintern-keyword "_EXTRA") kwd-alist)
7563                     (assq (idlwave-sintern-keyword "_REF_EXTRA") kwd-alist)))
7564          (completion-ignore-case t)
7565          candidates)
7566     (cond ((assq kwd kwd-alist) 
7567            kwd)
7568           ((setq candidates (all-completions kwd kwd-alist))
7569            (if (= (length candidates) 1)
7570                (car candidates)
7571              candidates))
7572           ((and entry extra)
7573            ;; Inheritance may cause this keyword to be correct 
7574            keyword)
7575           (entry
7576            ;; We do know the function, which does not have the keyword.
7577            nil)
7578           (t
7579            ;; We do not know the function, so this just might be a correct
7580            ;; keyword - return it as it is.
7581            keyword))))
7582
7583 (defvar idlwave-rinfo-mouse-map (make-sparse-keymap))
7584 (defvar idlwave-rinfo-map (make-sparse-keymap))
7585 (define-key idlwave-rinfo-mouse-map 
7586   (if (featurep 'xemacs) [button2] [mouse-2])
7587   'idlwave-mouse-active-rinfo)
7588 (define-key idlwave-rinfo-mouse-map 
7589   (if (featurep 'xemacs) [(shift button2)] [(shift mouse-2)])
7590   'idlwave-mouse-active-rinfo-shift)
7591 (define-key idlwave-rinfo-mouse-map 
7592   (if (featurep 'xemacs) [button3] [mouse-3])
7593   'idlwave-mouse-active-rinfo-right)
7594 (define-key idlwave-rinfo-mouse-map " " 'idlwave-active-rinfo-space)
7595 (define-key idlwave-rinfo-map "q" 'idlwave-quit-help)
7596 (define-key idlwave-rinfo-mouse-map "q" 'idlwave-quit-help)
7597 (defvar idlwave-popup-source nil)
7598 (defvar idlwave-rinfo-marker (make-marker))
7599
7600 (defun idlwave-quit-help ()
7601   (interactive)
7602   (let ((ri-window (get-buffer-window "*Help*"))
7603         (olh-window (get-buffer-window "*IDLWAVE Help*")))
7604     (when (and olh-window
7605                (fboundp 'idlwave-help-quit))
7606       (select-window olh-window)
7607       (idlwave-help-quit))
7608     (when (window-live-p ri-window)
7609       (delete-window ri-window))))
7610
7611 (defun idlwave-display-calling-sequence (name type class
7612                                               &optional initial-class)
7613   ;; Display the calling sequence of module NAME, type TYPE in class CLASS.
7614   (let* ((initial-class (or initial-class class))
7615          (entry (or (idlwave-best-rinfo-assq name type class
7616                                              (idlwave-routines))
7617                     (idlwave-rinfo-assq name type class 
7618                                         idlwave-unresolved-routines)))
7619          (name (or (car entry) name))
7620          (class (or (nth 2 entry) class))
7621          (superclasses (idlwave-all-class-inherits initial-class))
7622          (twins (idlwave-routine-twins entry))
7623          (dtwins (idlwave-study-twins twins))
7624          (all dtwins)
7625          (system (eq (car (nth 3 entry)) 'system))
7626          (calling-seq (nth 4 entry))
7627          (keywords (idlwave-entry-keywords entry 'do-link))
7628          (html-file (car (nth 5 entry)))
7629          (help-echo-kwd
7630           "Button2: Insert KEYWORD (SHIFT=`/KEYWORD') | Button3: Online Help ")
7631          (help-echo-use
7632           "Button2/3: Online Help")
7633          (help-echo-src
7634           "Button2: Jump to source and back | Button3: Source in Help window.")
7635          (help-echo-class
7636           "Button2: Display info about same method in superclass")
7637          (col 0)
7638          (data (list name type class (current-buffer) nil initial-class))
7639          (km-prop (if (featurep 'xemacs) 'keymap 'local-map))
7640          (face 'idlwave-help-link-face)
7641          beg props win cnt total)
7642     ;; Fix keywords, but don't add chained super-classes, since these 
7643     ;; are shown separately for that super-class
7644     (setq keywords (idlwave-fix-keywords name type class keywords))
7645     (cond
7646      ((null entry)
7647       (error "No %s %s known %s" type name
7648              (if initial-class (concat "in class " initial-class) "")))
7649      ((or (null name) (equal name ""))
7650       (error "No function or procedure call at point"))
7651      ((null calling-seq)
7652       (error "Calling sequence of %s %s not available" type name))
7653      (t
7654       (save-excursion
7655         (move-marker idlwave-rinfo-marker (point))
7656         (set-buffer (get-buffer-create "*Help*"))
7657         (use-local-map idlwave-rinfo-map)
7658         (setq buffer-read-only nil)
7659         (erase-buffer)
7660         (set (make-local-variable 'idlwave-popup-source) nil)
7661         (set (make-local-variable 'idlwave-current-obj_new-class)
7662                                   idlwave-current-obj_new-class)
7663         (when superclasses
7664           (setq props (list 'mouse-face 'highlight
7665                             km-prop idlwave-rinfo-mouse-map
7666                             'help-echo help-echo-class
7667                             'data (cons 'class data)))
7668           (let ((classes (cons initial-class superclasses)) c)
7669             (insert "Classes: ")
7670             (while (setq c (pop classes))
7671               (insert " ")
7672               (setq beg (point))
7673               (insert c)
7674               (if (equal (downcase c) (downcase class))
7675                   (add-text-properties beg (point) (list 'face 'bold))
7676                 ;; If Method exists in a different class link it
7677                 (if (idlwave-rinfo-assq name type c (idlwave-routines))
7678                     (add-text-properties beg (point) props))))
7679             (insert "\n")))
7680         (setq props (list 'mouse-face 'highlight
7681                           km-prop idlwave-rinfo-mouse-map
7682                           'help-echo help-echo-use
7683                           'data (cons 'usage data)))
7684         (if html-file (setq props (append (list 'face face 'link html-file) 
7685                                           props)))
7686         (insert "Usage:    ")
7687         (setq beg (point))
7688         (insert (if class
7689                     (format calling-seq class name)
7690                   (format calling-seq name))
7691                 "\n")
7692         (add-text-properties beg (point) props)
7693         
7694         (insert "Keywords:")
7695         (if (null keywords)
7696             (insert " No keywords accepted.")
7697           (setq col 9)
7698           (mapcar
7699            (lambda (x)
7700              (if (>= (+ col 1 (length (car x))) 
7701                      (window-width))
7702                  (progn
7703                    (insert "\n         ")
7704                    (setq col 9)))
7705              (insert " ")
7706              (setq beg (point)
7707                    ;; Relevant keywords already have link property attached
7708                    props (list 'mouse-face 'highlight
7709                                km-prop idlwave-rinfo-mouse-map
7710                                'data (cons 'keyword data)
7711                                'help-echo help-echo-kwd
7712                                'keyword (car x)))
7713              (if system (setq props (append (list 'face face) props)))
7714              (insert (car x))
7715              (add-text-properties beg (point) props)
7716              (setq col (+ col 1 (length (car x)))))
7717            keywords))
7718         
7719         (setq cnt 1 total (length all))
7720         ;; Here entry is (key file (list of type-conses))
7721         (while (setq entry (pop all))
7722           (setq props (list 'mouse-face 'highlight
7723                             km-prop idlwave-rinfo-mouse-map
7724                             'help-echo help-echo-src
7725                             'source (list (car (car (nth 2 entry))) ;type
7726                                           (nth 1 entry)
7727                                           nil
7728                                           (cdr (car (nth 2 entry))))
7729                             'data (cons 'source data)))
7730           (idlwave-insert-source-location
7731            (format "\n%-8s  %s" 
7732                    (if (equal cnt 1)
7733                        (if (> total 1) "Sources:" "Source:")
7734                      "")
7735                    (if (> total 1) "- " ""))
7736            entry props)
7737           (incf cnt)
7738           (when (and all (> cnt idlwave-rinfo-max-source-lines))
7739             ;; No more source lines, please
7740             (insert (format 
7741                      "\n          Source information truncated to %d entries."
7742                      idlwave-rinfo-max-source-lines))
7743             (setq all nil)))
7744
7745         (setq buffer-read-only t))
7746       (display-buffer "*Help*")
7747       (if (and (setq win (get-buffer-window "*Help*"))
7748                idlwave-resize-routine-help-window)
7749           (progn
7750             (let ((ww (selected-window)))
7751               (unwind-protect
7752                   (progn
7753                     (select-window win)
7754                     (enlarge-window (- (/ (frame-height) 2) 
7755                                        (window-height)))
7756                     (shrink-window-if-larger-than-buffer))
7757                 (select-window ww)))))))))
7758
7759 (defun idlwave-insert-source-location (prefix entry &optional file-props)
7760   "Insert a source location into the routine info buffer.
7761 Start line with PREFIX.  If a file name is inserted, add FILE-PROPS to
7762 it."
7763   (let* ((key (car entry))
7764          (file (nth 1 entry))
7765          (types (nth 2 entry))
7766          (shell-flag (assq 'compiled types))
7767          (buffer-flag (assq 'buffer types))
7768          (user-flag (assq 'user types))
7769          (lib-flag (assq 'lib types))
7770          (ndupl (or (and buffer-flag (idlwave-count-memq 'buffer types))
7771                     (and user-flag (idlwave-count-memq 'user types))
7772                     (and lib-flag (idlwave-count-memq 'lib types))
7773                     1))
7774          (doflags t)
7775          beg special)
7776
7777     (insert prefix)
7778
7779     (cond
7780      ((eq key 'system)
7781       (setq doflags nil)
7782       (insert "System    "))
7783
7784      ((eq key 'builtin)
7785       (setq doflags nil)
7786       (insert "Builtin   "))
7787
7788      ((and (not file) shell-flag)
7789       (insert "Unresolved"))
7790
7791      ((null file)               
7792       (insert "ERROR"))
7793      
7794      ((idlwave-syslib-p file)
7795       (if (string-match "obsolete" (file-name-directory file))
7796           (insert "Obsolete  ")
7797         (insert "SystemLib ")))
7798
7799      ;; New special syntax: taken directly from routine-info for
7800      ;; library catalog routines
7801      ((setq special (or (cdr lib-flag) (cdr user-flag)))
7802       (insert (format "%-10s" special)))
7803
7804      ;; Old special syntax: a matching regexp
7805      ((setq special (idlwave-special-lib-test file))
7806       (insert (format "%-10s" special)))
7807      
7808      ;; Catch-all with file
7809      ((idlwave-lib-p file)      (insert "Library   "))
7810
7811      ;; Sanity catch all
7812      (t                         (insert "Other     ")))
7813
7814     (when doflags
7815       (insert (concat
7816                "  ["
7817                (if lib-flag "L" "-")
7818                (if user-flag "C" "-")
7819                (if shell-flag "S" "-")
7820                (if buffer-flag "B" "-")
7821                "] ")))
7822     (when (> ndupl 1) 
7823       (setq beg (point))
7824       (insert (format "(%dx) " ndupl))
7825       (add-text-properties beg (point) (list 'face 'bold)))
7826     (when (and file (not (equal file "")))
7827       (setq beg (point))
7828       (insert (apply 'abbreviate-file-name
7829                      (if (featurep 'xemacs) (list file t) (list file))))
7830       (if file-props
7831           (add-text-properties beg (point) file-props)))))
7832
7833 (defun idlwave-special-lib-test (file)
7834   "Check the path of FILE against the regexps which define special libs.
7835 Return the name of the special lib if there is a match."
7836   (let ((alist idlwave-special-lib-alist)
7837         entry rtn)
7838     (cond
7839      ((stringp file)
7840       (while (setq entry (pop alist))
7841         (if (string-match (car entry) file)
7842             (setq rtn (cdr entry)
7843                   alist nil)))
7844       rtn)
7845      (t nil))))
7846   
7847 (defun idlwave-mouse-active-rinfo-right (ev)
7848   (interactive "e")
7849   (idlwave-mouse-active-rinfo ev 'right))
7850
7851 (defun idlwave-mouse-active-rinfo-shift (ev)
7852   (interactive "e")
7853   (idlwave-mouse-active-rinfo ev nil 'shift))
7854
7855 (defun idlwave-active-rinfo-space ()
7856   (interactive)
7857   (idlwave-mouse-active-rinfo nil 'right))
7858
7859 (defun idlwave-mouse-active-rinfo (ev &optional right shift)
7860   "Does the mouse actions in the routine info buffer.
7861 Optional args RIGHT and SHIFT indicate, if mouse-3 was used, and if SHIFT
7862 was pressed."
7863   (interactive "e")
7864   (if ev (mouse-set-point ev))
7865   (let (data id name type class buf bufwin source word initial-class)
7866     (setq data (get-text-property (point) 'data)
7867           source (get-text-property (point) 'source)
7868           keyword (get-text-property (point) 'keyword)
7869           link (get-text-property (point) 'link)
7870           id (car data)
7871           name (nth 1 data) type (nth 2 data) class (nth 3 data)
7872           buf (nth 4 data)
7873           initial-class (nth 6 data)
7874           word (idlwave-this-word)
7875           bufwin (get-buffer-window buf t))
7876
7877     (cond ((eq id 'class) ; Switch class being displayed
7878            (if (window-live-p bufwin) (select-window bufwin))
7879            (idlwave-display-calling-sequence 
7880             (idlwave-sintern-method name)
7881             type (idlwave-sintern-class word) 
7882             initial-class))
7883           ((eq id 'usage) ; Online help on this routine
7884            (idlwave-online-help link name type class))
7885           ((eq id 'source) ; Source in help or buffer
7886            (if right ; In help
7887                (let ((idlwave-extra-help-function 'idlwave-help-with-source)
7888                      (idlwave-help-source-try-header nil)
7889                      ;; Fake idlwave-routines so help will find the right entry
7890                      (idlwave-routines
7891                       (list (list name type class source ""))))
7892                  (idlwave-help-get-special-help name type class nil))
7893              ;; Otherwise just pop to the source
7894              (setq idlwave-popup-source (not idlwave-popup-source))
7895              (if idlwave-popup-source
7896                  (condition-case err
7897                      (idlwave-do-find-module name type class source)
7898                    (error
7899                     (setq idlwave-popup-source nil)
7900                     (if (window-live-p bufwin) (select-window bufwin))
7901                     (error (nth 1 err))))
7902                (if bufwin
7903                    (select-window bufwin)
7904                  (pop-to-buffer buf))
7905                (goto-char (marker-position idlwave-rinfo-marker)))))
7906           ((eq id 'keyword)
7907            (if right
7908                (idlwave-online-help link name type class keyword)
7909              (idlwave-rinfo-insert-keyword keyword buf shift))))))
7910
7911 (defun idlwave-rinfo-insert-keyword (keyword buffer &optional shift)
7912   "Insert KEYWORD in BUFFER.  Make sure buffer is displayed in a window."
7913   (let ((bwin (get-buffer-window buffer)))
7914     (if idlwave-complete-empty-string-as-lower-case
7915         (setq keyword (downcase keyword)))
7916     (if bwin
7917         (select-window bwin)
7918       (pop-to-buffer buffer)
7919       (setq bwin (get-buffer-window buffer)))
7920     (if (eq (preceding-char) ?/)
7921         (insert keyword)
7922       (unless (save-excursion 
7923                 (re-search-backward
7924                  "[(,][ \t]*\\(\\$[ \t]*\\(;.*\\)?\n\\)?[ \t]*\\=" 
7925                  (min (- (point) 100) (point-min)) t))
7926         (insert ", "))
7927       (if shift (insert "/"))
7928       (insert keyword)
7929       (if (and (not shift)
7930                idlwave-keyword-completion-adds-equal)
7931           (insert "=")))))
7932
7933 (defun idlwave-list-buffer-load-path-shadows (&optional arg)
7934   "List the load path shadows of all routines defined in current buffer."
7935   (interactive "P")
7936   (idlwave-routines)
7937   (if (eq major-mode 'idlwave-mode)
7938       (idlwave-list-load-path-shadows
7939        nil (idlwave-update-current-buffer-info 'save-buffer)
7940        "in current buffer")
7941     (error "Current buffer is not in idlwave-mode")))
7942
7943 (defun idlwave-list-shell-load-path-shadows (&optional arg)
7944   "List the load path shadows of all routines compiled under the shell.
7945 This is very useful for checking an IDL application.  Just compile the
7946 application, do RESOLVE_ALL, and `C-c C-i' to compile all referenced
7947 routines and update IDLWAVE internal info.  Then check for shadowing
7948 with this command."
7949   (interactive "P")
7950   (cond
7951    ((or (not (fboundp 'idlwave-shell-is-running))
7952         (not (idlwave-shell-is-running)))
7953     (error "Shell is not running"))
7954    ((null idlwave-compiled-routines)
7955     (error "No compiled routines.  Maybe you need to update with `C-c C-i'"))
7956    (t
7957     (idlwave-list-load-path-shadows nil idlwave-compiled-routines
7958                                     "in the shell"))))
7959
7960 (defun idlwave-list-all-load-path-shadows (&optional arg)
7961   "List the load path shadows of all routines known to IDLWAVE."
7962   (interactive "P")
7963   (idlwave-list-load-path-shadows nil nil "globally"))
7964
7965 (defun idlwave-list-load-path-shadows (arg &optional special-routines loc)
7966   "List the routines which are defined multiple times.
7967 Search the information IDLWAVE has about IDL routines for multiple
7968 definitions.
7969 When SPECIAL-ROUTINES in non-nil, only look for shadows of these routines.
7970
7971 When IDL hits a routine call which is not defined, it will search on
7972 the load path in order to find a definition.  The output of this
7973 command can be used to detect possible name clashes during this process."
7974   (idlwave-routines)  ; Make sure everything is loaded.
7975   (unless (or idlwave-user-catalog-routines idlwave-library-catalog-routines)
7976     (or (y-or-n-p 
7977          "You don't have any user or library catalogs.  Continue anyway? ")
7978         (error "Abort")))
7979   (let* ((routines (append idlwave-system-routines
7980                            idlwave-compiled-routines
7981                            idlwave-library-catalog-routines
7982                            idlwave-user-catalog-routines
7983                            idlwave-buffer-routines
7984                            nil))
7985          (km-prop (if (featurep 'xemacs) 'keymap 'local-map))
7986          (keymap (make-sparse-keymap))
7987          (props (list 'mouse-face 'highlight
7988                       km-prop keymap
7989                       'help-echo "Mouse2: Find source"))      
7990          (nroutines (length (or special-routines routines)))
7991          (step (/ nroutines 99))
7992          (n 0)
7993          (next-perc 1)
7994          (cnt 0)
7995          (idlwave-sort-prefer-buffer-info nil)
7996          routine twins dtwins twin done props1 lroutines)
7997
7998     (if special-routines
7999         ;; Just looking for shadows of a few special routines
8000         (setq lroutines routines
8001               routines special-routines))
8002
8003     (message "Sorting routines...")
8004     (setq routines (sort routines
8005                          (lambda (a b)
8006                            (string< (downcase (idlwave-make-full-name
8007                                                (nth 2 a) (car a)))
8008                                     (downcase (idlwave-make-full-name
8009                                                (nth 2 b) (car b)))))))
8010     (message "Sorting routines...done")
8011
8012     (define-key keymap (if (featurep 'xemacs) [(button2)] [(mouse-2)])
8013       (lambda (ev) 
8014         (interactive "e")
8015         (mouse-set-point ev)
8016         (apply 'idlwave-do-find-module
8017                (get-text-property (point) 'find-args))))
8018     (define-key keymap [(return)]
8019       (lambda () 
8020         (interactive)
8021         (apply 'idlwave-do-find-module
8022                (get-text-property (point) 'find-args))))
8023     (message "Compiling list...( 0%%)")
8024     (save-excursion
8025       (set-buffer (get-buffer-create "*Shadows*"))
8026       (setq buffer-read-only nil)
8027       (erase-buffer)
8028       (while (setq routine (pop routines))
8029         (setq n (1+ n))
8030         (if (= (* next-perc step) n)
8031             (progn
8032               (message "Compiling list...(%2d%%)" next-perc)
8033               (setq next-perc (1+ next-perc))))
8034         ;; Get a list of all twins
8035         (setq twins (idlwave-routine-twins routine (or lroutines routines)))
8036         (if (memq routine done)
8037             (setq dtwins nil)
8038           (setq dtwins (idlwave-study-twins twins)))
8039         ;; Mark all twins as dealt with
8040         (setq done (append twins done))
8041         (when (or (> (length dtwins) 1)
8042                   (> (idlwave-count-memq 'lib (nth 2 (car dtwins))) 1)
8043                   (> (idlwave-count-memq 'user (nth 2 (car dtwins))) 1)
8044                   (> (idlwave-count-memq 'buffer (nth 2 (car dtwins))) 1))
8045           (incf cnt)
8046           (insert (format "\n%s%s"
8047                           (idlwave-make-full-name (nth 2 routine) 
8048                                                   (car routine))
8049                           (if (eq (nth 1 routine) 'fun) "()" "")))
8050           (while (setq twin (pop dtwins))
8051             (setq props1 (append (list 'find-args
8052                                        (list (nth 0 routine) 
8053                                              (nth 1 routine) 
8054                                              (nth 2 routine)))
8055                                  props))
8056             (idlwave-insert-source-location "\n   - " twin props1))))
8057       (goto-char (point-min))
8058       (setq buffer-read-only t))
8059     (setq loc (or loc ""))
8060     (if (> cnt 0)
8061         (progn
8062           (display-buffer (get-buffer "*Shadows*"))
8063           (message "%d case%s of shadowing found %s"
8064                    cnt (if (= cnt 1) "" "s") loc))
8065       (message "No shadowing conflicts found %s" loc))))
8066
8067 (defun idlwave-print-source (routine)
8068   (let* ((source (nth 3 routine))
8069          (stype (car source))
8070          (sfile (idlwave-routine-source-file source)))
8071     (if (idlwave-syslib-p sfile) (setq stype 'syslib))
8072     (if (and (eq stype 'compiled)
8073              (or (not (stringp sfile))
8074                  (not (string-match "\\S-" sfile))))
8075         (setq stype 'unresolved))
8076     (princ (format "      %-10s %s\n" 
8077                    stype
8078                    (if sfile sfile "No source code available")))))
8079
8080 (defun idlwave-routine-twins (entry &optional list)
8081   "Return all twin entries of ENTRY in LIST.
8082 LIST defaults to `idlwave-routines'.
8083 Twin entries are those which have the same name, type, and class.
8084 ENTRY will also be returned, as the first item of this list."
8085   (let* ((name (car entry))
8086          (type (nth 1 entry))
8087          (class (nth 2 entry))
8088          (candidates (idlwave-all-assq name (or list (idlwave-routines))))
8089          twins candidate)
8090     (while (setq candidate (pop candidates))
8091       (if (and (not (eq candidate entry))
8092                (eq type (nth 1 candidate))
8093                (eq class (nth 2 candidate)))
8094           (push candidate twins)))
8095     (if (setq candidate (idlwave-rinfo-assq name type class 
8096                                             idlwave-unresolved-routines))
8097         (push candidate twins))
8098     (cons entry (nreverse twins))))
8099
8100 (defun idlwave-study-twins (entries)
8101   "Return dangerous twins of first entry in ENTRIES.  
8102 Dangerous twins are routines with same name, but in different files on
8103 the load path.  If a file is in the system library and has an entry in
8104 the `idlwave-system-routines' list, we omit the latter as
8105 non-dangerous because many IDL routines are implemented as library
8106 routines, and may have been scanned."
8107   (let* ((entry (car entries))
8108          (name (car entry))      ; 
8109          (type (nth 1 entry))    ; Must be bound for
8110          (class (nth 2 entry))   ;  idlwave-routine-twin-compare
8111          (cnt 0)
8112          source type type-cons file alist syslibp key)
8113     (while (setq entry (pop entries))
8114       (incf cnt)
8115       (setq source (nth 3 entry)
8116             type (car source)
8117             type-cons (cons type (nth 3 source))
8118             file (idlwave-routine-source-file source))
8119
8120       ;; Make KEY to index entry properly
8121       (setq key (cond ((eq type 'system) type)
8122                       (file (file-truename file))
8123                       (t 'unresolved)))
8124
8125       ;; Check for an entry in the system library
8126       (if (and file 
8127                (not syslibp)
8128                (idlwave-syslib-p file))
8129           (setq syslibp t))
8130       
8131       ;; If there's more than one matching entry for the same file, just
8132       ;; append the type-cons to the type list.
8133       (if (setq entry (assoc key alist))
8134           (push type-cons (nth 2 entry))
8135         (push (list key file (list type-cons)) alist)))
8136     
8137     (setq alist (nreverse alist))
8138     
8139     (when syslibp
8140       ;; File is in system *library* - remove any 'system entry
8141       (setq alist (delq (assq 'system alist) alist)))
8142     
8143     ;; If 'system remains and we've scanned the syslib, it's a builtin
8144     ;; (rather than a !DIR/lib/.pro file bundled as source).
8145     (when (and (idlwave-syslib-scanned-p)
8146                (setq entry (assoc 'system alist)))
8147       (setcar entry 'builtin))
8148     (sort alist 'idlwave-routine-twin-compare)))
8149
8150 (defvar name)
8151 (defvar type)
8152 (defvar class)
8153 (defvar idlwave-sort-prefer-buffer-info t
8154   "Internal variable used to influence `idlwave-routine-twin-compare'.")
8155
8156 (defmacro idlwave-xor (a b)
8157   `(and (or ,a ,b)
8158         (not (and ,a ,b))))
8159
8160 (defun idlwave-routine-entry-compare (a b)
8161   "Compare two routine info entries for sortiung.  This is the general case.
8162 It first compates class, names, and type.  If it turns out that A and B
8163 are twins (same name, class, and type), calls another routine which
8164 compares twins on the basis of their file names and path locations."
8165   (let ((name (car a)) (type (nth 1 a)) (class (nth 2 a)))
8166     (cond
8167      ((not (equal (idlwave-downcase-safe class)
8168                   (idlwave-downcase-safe (nth 2 b))))
8169       ;; Class decides
8170       (cond ((null (nth 2 b)) nil)
8171             ((null class) t)
8172             (t (string< (downcase class) (downcase (nth 2 b))))))
8173      ((not (equal (downcase name) (downcase (car b))))
8174       ;; Name decides
8175       (string< (downcase name) (downcase (car b))))
8176      ((not (eq type (nth 1 b)))
8177       ;; Type decides
8178       (< (if (eq type 'fun) 1 0) (if (eq (nth 1 b) 'fun) 1 0)))
8179      (t 
8180       ;; A and B are twins - so the decision is more complicated.
8181       ;; Call twin-compare with the proper arguments.
8182       (idlwave-routine-entry-compare-twins a b)))))
8183
8184 (defun idlwave-routine-entry-compare-twins (a b)
8185   "Compare two routine entries, under the assumption that they are
8186 twins.  This basically calls `idlwave-routine-twin-compare' with the
8187 correct args."
8188   (let* ((name (car a)) (type (nth 1 a)) (class (nth 2 a)) ; needed outside
8189          (asrc (nth 3 a))
8190          (atype (car asrc))
8191          (bsrc (nth 3 b))
8192          (btype (car bsrc))
8193          (afile (idlwave-routine-source-file asrc))
8194          (bfile (idlwave-routine-source-file bsrc)))
8195     (idlwave-routine-twin-compare
8196      (if (stringp afile)
8197          (list (file-truename afile) afile (list atype))
8198        (list atype afile (list atype)))
8199      (if (stringp bfile)
8200          (list (file-truename bfile) bfile (list btype))
8201        (list btype bfile (list btype))))
8202     ))
8203
8204 (defun idlwave-routine-twin-compare (a b)
8205   "Compare two routine twin entries for sorting.
8206 In here, A and B are not normal routine info entries, but special
8207 lists (KEY FILENAME (TYPES...)).
8208 This expects NAME TYPE CLASS to be bound to the right values."
8209   (let* (;; Dis-assemble entries
8210          (akey (car a))      (bkey (car b))
8211          (afile (nth 1 a))   (bfile (nth 1 b))
8212          (atypes (nth 2 a))  (btypes (nth 2 b))
8213          ;; System routines?
8214          (asysp (memq akey '(builtin system)))
8215          (bsysp (memq bkey '(builtin system)))
8216          ;; Compiled routines?
8217          (acompp (memq 'compiled atypes))
8218          (bcompp (memq 'compiled btypes))
8219          ;; Unresolved?
8220          (aunresp (or (eq akey 'unresolved)
8221                       (and acompp (not afile))))
8222          (bunresp (or (eq bkey 'unresolved)
8223                       (and bcompp (not bfile))))
8224          ;; Buffer info available?
8225          (abufp (memq 'buffer atypes))
8226          (bbufp (memq 'buffer btypes))
8227          ;; On search path?
8228          (tpath-alist (idlwave-true-path-alist))
8229          (apathp (and (stringp akey)
8230                       (assoc (file-name-directory akey) tpath-alist)))
8231          (bpathp (and (stringp bkey) 
8232                       (assoc (file-name-directory bkey) tpath-alist)))
8233          ;; How early on search path?  High number means early since we
8234          ;; measure the tail of the path list
8235          (anpath (length (memq apathp tpath-alist)))
8236          (bnpath (length (memq bpathp tpath-alist)))
8237          ;; Look at file names
8238          (aname (if (stringp afile) (downcase (file-name-nondirectory afile)) ""))
8239          (bname (if (stringp bfile) (downcase (file-name-nondirectory bfile)) ""))
8240          (fname-re (if class (format "\\`%s__\\(%s\\|define\\)\\.pro\\'"
8241                                      (regexp-quote (downcase class))
8242                                      (regexp-quote (downcase name)))
8243                      (format "\\`%s\\.pro" (regexp-quote (downcase name)))))
8244          ;; Is file name derived from the routine name?
8245          ;; Method file or class definition file?
8246          (anamep (string-match fname-re aname))
8247          (adefp (and class anamep (string= "define" (match-string 1 aname))))
8248          (bnamep (string-match fname-re bname))
8249          (bdefp (and class bnamep (string= "define" (match-string 1 bname)))))
8250
8251     ;; Now: follow JD's ideas about sorting.  Looks really simple now,
8252     ;; doesn't it?  The difficult stuff is hidden above...
8253     (cond
8254      ((idlwave-xor asysp  bsysp)       asysp)   ; System entries first
8255      ((idlwave-xor aunresp bunresp)    bunresp) ; Unresolved last
8256      ((and idlwave-sort-prefer-buffer-info
8257            (idlwave-xor abufp bbufp))  abufp)   ; Buffers before non-buffers
8258      ((idlwave-xor acompp bcompp)      acompp)  ; Compiled entries
8259      ((idlwave-xor apathp bpathp)      apathp)  ; Library before non-library
8260      ((idlwave-xor anamep bnamep)      anamep)  ; Correct file names first
8261      ((and class anamep bnamep                  ; both file names match ->
8262            (idlwave-xor adefp bdefp))  bdefp)   ; __define after __method
8263      ((> anpath bnpath)                t)       ; Who is first on path?
8264      (t                                nil))))  ; Default
8265
8266 (defun idlwave-routine-source-file (source)
8267   (if (nth 2 source) 
8268       (expand-file-name (nth 1 source) (nth 2 source))
8269     (nth 1 source)))
8270
8271 (defun idlwave-downcase-safe (string)
8272   "Donwcase if string, else return unchanged."
8273   (if (stringp string)
8274       (downcase string)
8275     string))
8276
8277 (defun idlwave-count-eq (elt list)
8278   "How often is ELT in LIST?"
8279   (length (delq nil (mapcar (lambda (x) (eq x elt)) list))))
8280
8281 (defun idlwave-count-memq (elt alist)
8282   "How often is ELT a key in ALIST?"
8283   (length (delq nil (mapcar (lambda (x) (eq (car x) elt)) alist))))
8284
8285 (defun idlwave-syslib-p (file)
8286   "Non-nil if FILE is in the system library."
8287   (let* ((true-syslib (file-name-as-directory
8288                        (file-truename
8289                         (expand-file-name "lib" (idlwave-sys-dir)))))
8290          (true-file (file-truename file)))
8291     (string-match (concat "^" (regexp-quote true-syslib)) true-file)))
8292
8293 (defun idlwave-lib-p (file)
8294   "Non-nil if file is in the library"
8295   (let ((true-dir (file-name-directory (file-truename file))))
8296     (assoc true-dir (idlwave-true-path-alist))))
8297
8298 (defun idlwave-path-alist-add-flag (list-entry flag)
8299   "Add a flag to the path list entry, if not set."
8300   (let ((flags (cdr list-entry)))
8301     (add-to-list 'flags flag)
8302     (setcdr list-entry flags)))
8303
8304 (defun idlwave-path-alist-remove-flag (list-entry flag)
8305   "Remove a flag to the path list entry, if set."
8306   (let ((flags (delq flag (cdr list-entry))))
8307     (setcdr list-entry flags)))
8308
8309 (defun idlwave-true-path-alist ()
8310   "Return `idlwave-path-alist' alist with true-names.
8311 Info is cached, but relies on the functions setting `idlwave-path-alist'
8312 to reset the variable `idlwave-true-path-alist' to nil."
8313   (or idlwave-true-path-alist
8314       (setq idlwave-true-path-alist
8315             (mapcar (lambda(x) (cons
8316                                 (file-name-as-directory
8317                                  (file-truename
8318                                   (directory-file-name
8319                                    (car x))))
8320                                 (cdr x)))
8321                     idlwave-path-alist))))
8322
8323 (defun idlwave-syslib-scanned-p ()
8324   "Non-nil if the system lib file !DIR/lib has been scanned."
8325   (let* ((true-syslib (file-name-as-directory
8326                        (file-truename
8327                         (expand-file-name "lib" (idlwave-sys-dir))))))
8328     (cdr (assoc true-syslib (idlwave-true-path-alist)))))
8329
8330 ;; ----------------------------------------------------------------------------
8331 ;;
8332 ;; Online Help display
8333
8334
8335 ;; ----------------------------------------------------------------------------
8336 ;;
8337 ;; Additions for use with imenu.el and func-menu.el
8338 ;; (pop-up a list of IDL units in the current file).
8339 ;;
8340
8341 (defun idlwave-prev-index-position ()
8342   "Search for the previous procedure or function.
8343 Return nil if not found.  For use with imenu.el."
8344   (save-match-data
8345     (cond
8346      ((idlwave-find-key "\\<\\(pro\\|function\\)\\>" -1 'nomark))
8347      ;;   ((idlwave-find-key idlwave-begin-unit-reg 1 'nomark)
8348      (t nil))))
8349
8350 (defun idlwave-unit-name ()
8351   "Return the unit name.
8352 Assumes that point is at the beginning of the unit as found by
8353 `idlwave-prev-index-position'."
8354   (forward-sexp 2)
8355   (forward-sexp -1)
8356   (let ((begin (point)))
8357     (re-search-forward "[a-zA-Z][a-zA-Z0-9$_]+\\(::[a-zA-Z][a-zA-Z0-9$_]+\\)?")
8358     (if (fboundp 'buffer-substring-no-properties)
8359         (buffer-substring-no-properties begin (point))
8360       (buffer-substring begin (point)))))
8361
8362 (defalias 'idlwave-function-menu
8363   (condition-case nil
8364       (progn
8365         (require 'func-menu)
8366         'function-menu)
8367     (error (condition-case nil
8368                (progn
8369                  (require 'imenu)
8370                  'imenu)
8371              (error nil)))))
8372
8373 ;; Here we hack func-menu.el in order to support this new mode.
8374 ;; The latest versions of func-menu.el already have this stuff in, so
8375 ;; we hack only if it is not already there.
8376 (when (fboundp 'eval-after-load)
8377   (eval-after-load "func-menu"
8378     '(progn
8379        (or (assq 'idlwave-mode fume-function-name-regexp-alist)
8380            (not (boundp 'fume-function-name-regexp-idl))      ; avoid problems
8381            (setq fume-function-name-regexp-alist
8382                  (cons '(idlwave-mode . fume-function-name-regexp-idl)
8383                        fume-function-name-regexp-alist)))
8384        (or (assq 'idlwave-mode fume-find-function-name-method-alist)
8385            (not (fboundp 'fume-find-next-idl-function-name))  ; avoid problems
8386            (setq fume-find-function-name-method-alist
8387                  (cons '(idlwave-mode . fume-find-next-idl-function-name)
8388                        fume-find-function-name-method-alist))))))
8389
8390 (defun idlwave-edit-in-idlde ()
8391   "Edit the current file in IDL Development environment."
8392   (interactive)
8393   (start-process "idldeclient" nil
8394                  idlwave-shell-explicit-file-name "-c" "-e"
8395                  (buffer-file-name) "&"))
8396                 
8397 (defun idlwave-launch-idlhelp ()
8398   "Start the IDLhelp application."
8399   (interactive)
8400   (start-process "idlhelp" nil idlwave-help-application))
8401  
8402 ;; Menus - using easymenu.el
8403 (defvar idlwave-mode-menu-def
8404   `("IDLWAVE"
8405     ["PRO/FUNC menu" idlwave-function-menu t]
8406     ("Motion"
8407      ["Subprogram Start" idlwave-beginning-of-subprogram t]
8408      ["Subprogram End" idlwave-end-of-subprogram t]
8409      ["Block Start" idlwave-beginning-of-block t]
8410      ["Block End" idlwave-end-of-block t]
8411      ["Up Block" idlwave-backward-up-block t]
8412      ["Down Block" idlwave-down-block t]
8413      ["Skip Block Backward" idlwave-backward-block t]
8414      ["Skip Block Forward" idlwave-forward-block t])
8415     ("Mark"
8416      ["Subprogram" idlwave-mark-subprogram t]
8417      ["Block" idlwave-mark-block t]
8418      ["Header" idlwave-mark-doclib t])
8419     ("Format"
8420      ["Indent Subprogram" idlwave-indent-subprogram t]
8421      ["(Un)Comment Region" idlwave-toggle-comment-region "C-c ;"]
8422      ["Continue/Split line" idlwave-split-line t]
8423      "--"
8424      ["Toggle Auto Fill" idlwave-auto-fill-mode :style toggle
8425       :selected (symbol-value idlwave-fill-function)])
8426     ("Templates"
8427      ["Procedure" idlwave-procedure t]
8428      ["Function" idlwave-function t]
8429      ["Doc Header" idlwave-doc-header t]
8430      ["Log" idlwave-doc-modification t]
8431      "--"
8432      ["Case" idlwave-case t]
8433      ["For" idlwave-for t]
8434      ["Repeat" idlwave-repeat t]
8435      ["While" idlwave-while t]
8436      "--"
8437      ["Close Block" idlwave-close-block t])
8438     ("Completion"
8439      ["Complete" idlwave-complete t]
8440      ("Complete Special"
8441       ["1 Procedure Name" (idlwave-complete 'procedure) t]
8442       ["2 Procedure Keyword" (idlwave-complete 'procedure-keyword) t]
8443       "--"
8444       ["3 Function Name" (idlwave-complete 'function) t]
8445       ["4 Function Keyword" (idlwave-complete 'function-keyword) t]
8446       "--"
8447       ["5 Procedure Method Name" (idlwave-complete 'procedure-method) t]
8448       ["6 Procedure Method Keyword" (idlwave-complete 'procedure-method-keyword) t]
8449       "--"
8450       ["7 Function Method Name" (idlwave-complete 'function-method) t]
8451       ["8 Function Method Keyword" (idlwave-complete 'function-method-keyword) t]
8452       "--"
8453       ["9 Class Name"  idlwave-complete-class t]))
8454     ("Routine Info"
8455      ["Show Routine Info" idlwave-routine-info t]
8456      ["Online Context Help" idlwave-context-help t]
8457      "--"
8458      ["Find Routine Source" idlwave-find-module t]
8459      ["Resolve Routine" idlwave-resolve (featurep 'idlw-shell)]
8460      "--"
8461      ["Update Routine Info" idlwave-update-routine-info t]
8462      "--"
8463      "IDL User Catalog"
8464      ["Select Catalog Directories" (idlwave-create-user-catalog-file nil) t]
8465      ["Scan Directories" (idlwave-update-routine-info '(16))
8466       (and idlwave-path-alist (not idlwave-catalog-process))]
8467      ["Scan Directories &" (idlwave-update-routine-info '(64))
8468       (and idlwave-path-alist (not idlwave-catalog-process))]
8469      "--"
8470      "Routine Shadows"
8471      ["Check Current Buffer" idlwave-list-buffer-load-path-shadows t]
8472      ["Check Compiled Routines" idlwave-list-shell-load-path-shadows t]
8473      ["Check Everything" idlwave-list-all-load-path-shadows t])
8474     ("Misc"
8475      ["Kill auto-created buffers" idlwave-kill-autoloaded-buffers t]
8476      "--"
8477      ["Insert TAB character" idlwave-hard-tab t])
8478      "--"
8479     ("External"
8480      ["Generate IDL tags" idlwave-make-tags t]
8481      ["Start IDL shell" idlwave-shell t]
8482      ["Edit file in IDLDE" idlwave-edit-in-idlde t]
8483      ["Launch IDL Help" idlwave-launch-idlhelp t])
8484     "--"
8485     ("Customize"
8486      ["Browse IDLWAVE Group" idlwave-customize t]
8487      "--"
8488      ["Build Full Customize Menu" idlwave-create-customize-menu 
8489       (fboundp 'customize-menu-create)])
8490     ("Documentation"
8491      ["Describe Mode" describe-mode t]
8492      ["Abbreviation List" idlwave-list-abbrevs t]
8493      "--"
8494      ["Commentary in idlwave.el" idlwave-show-commentary t]
8495      ["Commentary in idlw-shell.el" idlwave-shell-show-commentary t]
8496      "--"
8497      ["Info" idlwave-info t]
8498      "--"
8499      ["Launch IDL Help" idlwave-launch-idlhelp t])))
8500
8501 (defvar idlwave-mode-debug-menu-def
8502   '("Debug"
8503     ["Start IDL shell" idlwave-shell t]
8504     ["Save and .RUN buffer" idlwave-shell-save-and-run
8505      (and (boundp 'idlwave-shell-automatic-start) 
8506           idlwave-shell-automatic-start)]))
8507
8508 (if (or (featurep 'easymenu) (load "easymenu" t))
8509     (progn
8510       (easy-menu-define idlwave-mode-menu idlwave-mode-map 
8511                         "IDL and WAVE CL editing menu" 
8512                         idlwave-mode-menu-def)
8513       (easy-menu-define idlwave-mode-debug-menu idlwave-mode-map 
8514                         "IDL and WAVE CL editing menu" 
8515                         idlwave-mode-debug-menu-def)))
8516
8517 (defun idlwave-customize ()
8518   "Call the customize function with idlwave as argument."
8519   (interactive)
8520   ;; Try to load the code for the shell, so that we can customize it 
8521   ;; as well.
8522   (or (featurep 'idlw-shell)
8523       (load "idlw-shell" t))
8524   (customize-browse 'idlwave))
8525
8526 (defun idlwave-create-customize-menu ()
8527   "Create a full customization menu for IDLWAVE, insert it into the menu."
8528   (interactive)
8529   (if (fboundp 'customize-menu-create)
8530       (progn
8531         ;; Try to load the code for the shell, so that we can customize it 
8532         ;; as well.
8533         (or (featurep 'idlw-shell)
8534             (load "idlw-shell" t))
8535         (easy-menu-change 
8536          '("IDLWAVE") "Customize"
8537          `(["Browse IDLWAVE group" idlwave-customize t]
8538            "--"
8539            ,(customize-menu-create 'idlwave)
8540            ["Set" Custom-set t]
8541            ["Save" Custom-save t]
8542            ["Reset to Current" Custom-reset-current t]
8543            ["Reset to Saved" Custom-reset-saved t]
8544            ["Reset to Standard Settings" Custom-reset-standard t]))
8545         (message "\"IDLWAVE\"-menu now contains full customization menu"))
8546     (error "Cannot expand menu (outdated version of cus-edit.el)")))
8547
8548 (defun idlwave-show-commentary ()
8549   "Use the finder to view the file documentation from `idlwave.el'."
8550   (interactive)
8551   (require 'finder)
8552   (finder-commentary "idlwave.el"))
8553
8554 (defun idlwave-shell-show-commentary ()
8555   "Use the finder to view the file documentation from `idlw-shell.el'."
8556   (interactive)
8557   (require 'finder)
8558   (finder-commentary "idlw-shell.el"))
8559
8560 (defun idlwave-info ()
8561   "Read documentation for IDLWAVE in the info system."
8562   (interactive)
8563   (require 'info)
8564   (Info-goto-node "(idlwave)"))
8565
8566 (defun idlwave-list-abbrevs (arg)
8567   "Show the code abbreviations define in IDLWAVE mode.
8568 This lists all abbrevs where the replacement text differs from the input text.
8569 These are the ones the users want to learn to speed up their writing.
8570
8571 The function does *not* list abbrevs which replace a word with itself
8572 to call a hook.  These hooks are used to change the case of words or
8573 to blink the matching `begin', and the user does not need to know them.
8574
8575 With arg, list all abbrevs with the corresponding hook.
8576
8577 This function was written since `list-abbrevs' looks terrible for IDLWAVE mode."
8578
8579   (interactive "P")
8580   (let ((table (symbol-value 'idlwave-mode-abbrev-table))
8581         abbrevs
8582         str rpl func fmt (len-str 0) (len-rpl 0))
8583     (mapatoms 
8584      (lambda (sym)
8585        (if (symbol-value sym)
8586            (progn
8587              (setq str (symbol-name sym)
8588                    rpl (symbol-value sym)
8589                    func (symbol-function sym))
8590              (if arg
8591                  (setq func (prin1-to-string func))
8592                (if (and (listp func) (stringp (nth 2 func)))
8593                    (setq rpl (concat "EVAL: " (nth 2 func))
8594                          func "")
8595                  (setq func "")))
8596              (if (or arg (not (string= rpl str)))
8597                  (progn
8598                    (setq len-str (max len-str (length str)))
8599                    (setq len-rpl (max len-rpl (length rpl)))
8600                    (setq abbrevs (cons (list str rpl func) abbrevs)))))))
8601      table)
8602     ;; sort the list
8603     (setq abbrevs (sort abbrevs (lambda (a b) (string< (car a) (car b)))))
8604     ;; Make the format
8605     (setq fmt (format "%%-%ds   %%-%ds   %%s\n" len-str len-rpl))
8606     (with-output-to-temp-buffer "*Help*"
8607       (if arg
8608           (progn
8609             (princ "Abbreviations and Actions in IDLWAVE-Mode\n") 
8610             (princ "=========================================\n\n")
8611             (princ (format fmt "KEY" "REPLACE" "HOOK"))
8612             (princ (format fmt "---" "-------" "----")))
8613         (princ "Code Abbreviations and Templates in IDLWAVE-Mode\n")
8614         (princ "================================================\n\n")
8615         (princ (format fmt "KEY" "ACTION" ""))
8616         (princ (format fmt "---" "------" "")))
8617       (mapcar
8618        (lambda (list)
8619          (setq str (car list)
8620                rpl (nth 1 list)
8621                func (nth 2 list))
8622          (princ (format fmt str rpl func)))
8623        abbrevs)))
8624   ;; Make sure each abbreviation uses only one display line
8625   (save-excursion
8626     (set-buffer "*Help*")
8627     (setq truncate-lines t)))
8628
8629 ;; Add .pro files to speedbar for support, if it's loaded
8630 (eval-after-load "speedbar" '(speedbar-add-supported-extension ".pro"))
8631
8632 ;; Set an idle timer to load the routine info.
8633 ;; Will only work on systems which support this.
8634 (or idlwave-routines (idlwave-start-load-rinfo-timer))
8635
8636 ;; Run the hook
8637 (run-hooks 'idlwave-load-hook)
8638
8639 (provide 'idlwave)
8640
8641 ;;; idlwave.el ends here