1;; idlwave.el --- IDL editing mode for GNU Emacs
2
3;; Copyright (C) 1999-2021 Free Software Foundation, Inc.
4
5;; Authors: JD Smith <jd.smith@utoledo.edu>
6;;          Carsten Dominik <dominik@science.uva.nl>
7;;          Chris Chase <chase@att.com>
8;; Maintainer: emacs-devel@gnu.org
9;; Version: 6.1.22
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 3 of the License, or
17;; (at your option) 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.  If not, see <https://www.gnu.org/licenses/>.
26
27;;; Commentary:
28
29;; IDLWAVE enables feature-rich development and interaction with IDL,
30;; the Interactive Data Language.  It provides a compelling,
31;; full-featured alternative to the IDLDE development environment
32;; bundled with IDL.
33
34;; In the remotely distant past, based on pascal.el, though bears
35;; little resemblance to it now.
36;;
37;; Incorporates many ideas, such as abbrevs, action routines, and
38;; continuation line indenting, from wave.el.
39;; wave.el original written by Lubos Pochman, Precision Visuals, Boulder.
40;;
41;; See the mode description ("C-h m" in idlwave-mode or "C-h f idlwave-mode")
42;; for features, key bindings, and info.
43;; Also, Info format documentation is available with `M-x idlwave-info'
44;;
45;; New versions of IDLWAVE, documentation, and more information
46;; available from:
47;;                 http://github.com/jdtsmith/idlwave
48;;
49;; INSTALLATION
50;; ============
51;;
52;; Follow the instructions in the INSTALL file of the distribution.
53;; In short, put this file on your load path and add the following
54;; lines to your init file:
55;;
56;; (autoload 'idlwave-mode "idlwave" "IDLWAVE Mode" t)
57;; (autoload 'idlwave-shell "idlw-shell" "IDLWAVE Shell" t)
58;; (setq auto-mode-alist (cons '("\\.pro\\'" . idlwave-mode) auto-mode-alist))
59;;
60;;
61;; SOURCE
62;; ======
63;;
64;; The newest version of this file is available from the maintainer's
65;; Webpage:
66;;
67;;   http://github.com/jdtsmith/idlwave
68;;
69;; DOCUMENTATION
70;; =============
71;;
72;; IDLWAVE is documented online in info format.  A printable version
73;; of the documentation is available from the maintainers webpage (see
74;; SOURCE).
75;;
76;;
77;; ACKNOWLEDGMENTS
78;; ===============
79;;
80;;  Thanks to the following people for their contributions and comments:
81;;
82;;    Ulrik Dickow <dickow_at_nbi.dk>
83;;    Eric E. Dors <edors_at_lanl.gov>
84;;    Stein Vidar H. Haugan <s.v.h.haugan_at_astro.uio.no>
85;;    David Huenemoerder <dph_at_space.mit.edu>
86;;    Kevin Ivory <Kevin.Ivory_at_linmpi.mpg.de>
87;;    Dick Jackson <dick_at_d-jackson.com>
88;;    Xuyong Liu <liu_at_stsci.edu>
89;;    Simon Marshall <Simon.Marshall_at_esrin.esa.it>
90;;    Laurent Mugnier <mugnier_at_onera.fr>
91;;    Lubos Pochman <lubos_at_rsinc.com>
92;;    Bob Portmann <portmann_at_al.noaa.gov>
93;;    Patrick M. Ryan <pat_at_jaameri.gsfc.nasa.gov>
94;;    Marty Ryba <ryba_at_ll.mit.edu>
95;;    Paul Sorenson <aardvark62_at_msn.com>
96;;    Phil Sterne <sterne_at_dublin.llnl.gov>
97;;    Phil Williams <williams_at_irc.chmcc.org>
98;;
99;; CUSTOMIZATION:
100;; =============
101;;
102;; IDLWAVE has extensive customize support; to learn about the
103;; variables which control the mode's behavior, use `M-x
104;; idlwave-customize'.
105;;
106;; You can set your own preferred values with Customize, or with Lisp
107;; code in .emacs.  For an example of what to put into .emacs, check
108;; the TexInfo documentation or see a complete .emacs available at the
109;; website.
110;;
111;; KNOWN PROBLEMS:
112;; ==============
113;;
114;;   IDLWAVE support for the IDL-derived PV-WAVE CL language of Visual
115;;   Numerics, Inc. is growing less and less complete as the two
116;;   languages grow increasingly apart.  The mode probably shouldn't
117;;   even have "WAVE" in its title, but it's catchy, and was required
118;;   to avoid conflict with the CORBA idl.el mode.  Caveat WAVEor.
119;;
120;;   Moving the point backwards in conjunction with abbrev expansion
121;;   does not work as I would like it, but this is a problem with
122;;   emacs abbrev expansion done by the self-insert-command.  It ends
123;;   up inserting the character that expanded the abbrev after moving
124;;   point backward, e.g., "\cl" expanded with a space becomes
125;;   "LONG( )" with point before the close paren.  This is solved by
126;;   using a temporary function in `post-command-hook' - not pretty,
127;;   but it works.
128;;
129;;   Tabs and spaces are treated equally as whitespace when filling a
130;;   comment paragraph.  To accomplish this, tabs are permanently
131;;   replaced by spaces in the text surrounding the paragraph, which
132;;   may be an undesirable side-effect.  Replacing tabs with spaces is
133;;   limited to comments only and occurs only when a comment
134;;   paragraph is filled via `idlwave-fill-paragraph'.
135;;
136;;   Muti-statement lines (using "&") on block begin and end lines can
137;;   ruin the formatting.  For example, multiple end statements on a
138;;   line: endif & endif.  Using "&" outside of block begin/end lines
139;;   should be okay.
140;;
141;;   Determining the expression at point for printing and other
142;;   examination commands is somewhat rough: currently only fairly
143;;   simple entities are found.  You can always drag-select or examine
144;;   a pre-selected region.
145;;
146;;   When forcing completion of method keywords, the initial
147;;   query for a method has multiple entries for some methods.  Would
148;;   be too difficult to fix this hardly used case.
149;;
150
151;;; Code:
152
153
154(eval-when-compile (require 'cl-lib))
155(require 'idlw-help)
156
157;; For XEmacs
158(unless (fboundp 'line-beginning-position)
159  (defalias 'line-beginning-position 'point-at-bol))
160(unless (fboundp 'line-end-position)
161  (defalias 'line-end-position 'point-at-eol))
162(unless (fboundp 'char-valid-p)
163  (defalias 'char-valid-p 'characterp))
164(unless (fboundp 'match-string-no-properties)
165  (defalias 'match-string-no-properties 'match-string))
166
167(if (not (fboundp 'cancel-timer))
168    (condition-case nil
169	(require 'timer)
170      (error nil)))
171
172(declare-function idlwave-shell-get-path-info "idlw-shell")
173(declare-function idlwave-shell-temp-file "idlw-shell")
174(declare-function idlwave-shell-is-running "idlw-shell")
175(declare-function widget-value "wid-edit" (widget))
176(declare-function comint-dynamic-complete-filename "comint" ())
177
178(defgroup idlwave nil
179  "Major mode for editing IDL .pro files."
180  :tag "IDLWAVE"
181  :link '(url-link :tag "Home Page"
182		   "http://github.com/jdtsmith/idlwave")
183  :link '(emacs-commentary-link :tag "Commentary in idlw-shell.el"
184				"idlw-shell.el")
185  :link '(emacs-commentary-link :tag "Commentary in idlwave.el" "idlwave.el")
186  :link '(custom-manual "(idlwave)Top")
187  :prefix "idlwave"
188  :group 'languages)
189
190
191;;; Variables for indentation behavior ---------------------------------------
192
193(defgroup idlwave-code-formatting nil
194  "Indentation and formatting options for IDLWAVE mode."
195  :group 'idlwave)
196
197(defcustom idlwave-main-block-indent 2
198  "Extra indentation for the main block of code.
199That is the block between the FUNCTION/PRO statement and the END
200statement for that program unit."
201  :group 'idlwave-code-formatting
202  :type 'integer)
203
204(defcustom idlwave-block-indent 3
205  "Extra indentation applied to block lines.
206If you change this, you probably also want to change `idlwave-end-offset'."
207  :group 'idlwave-code-formatting
208  :type 'integer)
209
210(defcustom idlwave-end-offset -3
211  "Extra indentation applied to block END lines.
212A value equal to negative `idlwave-block-indent' will make END lines
213line up with the block BEGIN lines."
214  :group 'idlwave-code-formatting
215  :type 'integer)
216
217(defcustom idlwave-continuation-indent 3
218  "Extra indentation applied to continuation lines.
219This extra offset applies to the first of a set of continuation lines.
220The following lines receive the same indentation as the first."
221  :group 'idlwave-code-formatting
222  :type 'integer)
223
224(defcustom idlwave-max-extra-continuation-indent 40
225  "Maximum additional indentation for special continuation indent.
226Several special indentations are tried to help line up continuation
227lines in routine calls or definitions, other statements with
228parentheses, or assignment statements.  This variable specifies a
229maximum amount by which this special indentation can exceed the
230standard continuation indentation, otherwise defaulting to a fixed
231offset.  Set to 0 to effectively disable all special continuation
232indentation, or to a large number (like 100) to enable it in all
233cases.  See also `idlwave-indent-to-open-paren', which can override
234this variable."
235  :group 'idlwave-code-formatting
236  :type 'integer)
237
238(defcustom idlwave-indent-to-open-paren t
239  "Non-nil means, indent continuation lines to innermost open parenthesis.
240This indentation occurs even if otherwise disallowed by
241`idlwave-max-extra-continuation-indent'.  Matching parens and the
242interleaving args are lined up.  Example:
243
244  x = function_a(function_b(function_c( a, b, [1,2,3, $
245                                               4,5,6 $
246                                              ], $
247                                        c, d $
248                                      )))
249
250When this variable is nil, paren alignment may still occur, based on
251the value of `idlwave-max-extra-continuation-indent', which, if zero,
252would yield:
253
254  x = function_a(function_b(function_c( a, b, [1,2,3, $
255     4,5,6 $
256     ], $
257     c, d $
258     )))"
259  :group 'idlwave-code-formatting
260  :type 'boolean)
261
262(defcustom idlwave-indent-parens-nested nil
263  "Non-nil means, indent continuation lines with parens by nesting
264lines at consecutively deeper levels."
265 :group 'idlwave-code-formatting
266  :type 'boolean)
267
268
269(defcustom idlwave-hanging-indent t
270  "If set non-nil then comment paragraphs are indented under the
271hanging indent given by `idlwave-hang-indent-regexp' match in the first line
272of the paragraph."
273  :group 'idlwave-code-formatting
274  :type 'boolean)
275
276(defcustom idlwave-hang-indent-regexp "- "
277  "Regular expression matching the position of the hanging indent
278in the first line of a comment paragraph.  The size of the indent
279extends to the end of the match for the regular expression."
280  :group 'idlwave-code-formatting
281  :type 'regexp)
282
283(defcustom idlwave-use-last-hang-indent nil
284  "If non-nil then use last match on line for `idlwave-indent-regexp'."
285  :group 'idlwave-code-formatting
286  :type 'boolean)
287
288(defcustom idlwave-fill-comment-line-only t
289  "If non-nil then auto fill will only operate on comment lines."
290  :group 'idlwave-code-formatting
291  :type 'boolean)
292
293(defcustom idlwave-auto-fill-split-string t
294  "If non-nil then auto fill will split strings with the IDL `+' operator.
295When the line end falls within a string, string concatenation with the
296`+' operator will be used to distribute a long string over lines.
297If nil and a string is split then a terminal beep and warning are issued.
298
299This variable is ignored when `idlwave-fill-comment-line-only' is
300non-nil, since in this case code is not auto-filled."
301  :group 'idlwave-code-formatting
302  :type 'boolean)
303
304(defcustom idlwave-split-line-string t
305  "If non-nil then `idlwave-split-line' will split strings with `+'.
306When the splitting point of a line falls inside a string, split the string
307using the `+' string concatenation operator.  If nil and a string is
308split then a terminal beep and warning are issued."
309  :group 'idlwave-code-formatting
310  :type 'boolean)
311
312(defcustom idlwave-no-change-comment ";;;"
313  "The indentation of a comment that starts with this regular
314expression will not be changed.  Note that the indentation of a comment
315at the beginning of a line is never changed."
316  :group 'idlwave-code-formatting
317  :type 'string)
318
319(defcustom idlwave-begin-line-comment nil
320  "A comment anchored at the beginning of line.
321A comment matching this regular expression will not have its
322indentation changed.  If nil the default is \"^;\", i.e., any line
323beginning with a \";\".  Expressions for comments at the beginning of
324the line should begin with \"^\"."
325  :group 'idlwave-code-formatting
326  :type '(choice (const :tag "Any line beginning with `;'" nil)
327		 'regexp))
328
329(defcustom idlwave-code-comment ";;[^;]"
330  "A comment that starts with this regular expression on a line by
331itself is indented as if it is a part of IDL code.  As a result if
332the comment is not preceded by whitespace it is unchanged."
333  :group 'idlwave-code-formatting
334  :type 'regexp)
335
336;; Comments not matching any of the above will be indented as a
337;; right-margin comment, i.e., to a minimum of `comment-column'.
338
339;;; Routine Info and Completion ---------------------------------------
340
341(defgroup idlwave-routine-info nil
342  "Routine Info options for IDLWAVE mode."
343  :group 'idlwave)
344
345(defcustom idlwave-use-library-catalogs t
346  "Non-nil means search the IDL path for library catalog files.
347
348These files, named .idlwave_catalog, document routine information for
349individual directories and libraries of IDL .pro files.  Many popular
350libraries come with catalog files by default, so leaving this on is
351usually a good idea."
352  :group 'idlwave-routine-info
353  :type 'boolean)
354
355(defcustom idlwave-init-rinfo-when-idle-after 10
356  "Seconds of idle time before routine info is automatically initialized.
357Initializing the routine info can take a long time, in particular if a
358large number of library catalogs are involved.  When Emacs is idle for
359more than the number of seconds specified by this variable, it starts
360the initialization.  The process is split into five steps, in order to
361keep work interruption as short as possible.  If one of the steps
362finishes, and no user input has arrived in the mean time, initialization
363proceeds immediately to the next step.  A good value for this variable
364is about 1/3 of the time initialization take in your setup.  So if you
365have a fast machine and no problems with a slow network connection,
366don't hesitate to set this to 2 seconds.  A value of 0 means, don't
367initialize automatically, but instead wait until routine information is
368needed, and initialize then."
369  :group 'idlwave-routine-info
370  :type 'number)
371
372(defcustom idlwave-scan-all-buffers-for-routine-info t
373  "Non-nil means, scan buffers for IDL programs when updating info.
374The scanning is done by the command `idlwave-update-routine-info'.
375The following values are allowed:
376
377nil       Don't scan any buffers.
378t         Scan all `idlwave-mode' buffers in the current editing session.
379`current' Scan only the current buffer, but no other buffers."
380  :group 'idlwave-routine-info
381  :type '(choice
382	  (const :tag "No buffer" nil)
383	  (const :tag "All buffers" t)
384	  (const :tag "Current buffer only" current)))
385
386(defcustom idlwave-query-shell-for-routine-info t
387  "Non-nil means query the shell for info about compiled routines.
388Querying the shell is useful to get information about compiled modules,
389and it is turned on by default.  However, when you have a complete library
390scan, this is not necessary."
391  :group 'idlwave-routine-info
392  :type 'boolean)
393
394(defcustom idlwave-auto-routine-info-updates
395  '(find-file save-buffer kill-buffer compile-buffer)
396  "Controls under what circumstances routine info is updated automatically.
397Possible values:
398nil       Never
399t         All available
400\(...)     A list of circumstances.  Allowed members are:
401           find-file       Add info for new IDLWAVE buffers.
402           save-buffer     Update buffer info when buffer is saved
403           kill-buffer     Remove buffer info when buffer gets killed
404           compile-buffer  Update shell info after `idlwave-shell-save-and...'"
405  :group 'idlwave-routine-info
406  :type '(choice
407	  (const :tag "Never" nil)
408	  (const :tag "As often as possible" t)
409	  (set :tag "Checklist" :greedy t
410	       (const :tag "When visiting a file" find-file)
411	       (const :tag "When saving a buffer" save-buffer)
412	       (const :tag "After a buffer was killed" kill-buffer)
413	       (const :tag "After a buffer was compiled successfully, update shell info" compile-buffer))))
414
415(defcustom idlwave-rinfo-max-source-lines 5
416  "Maximum number of source files displayed in the Routine Info window.
417When an integer, it is the maximum number of source files displayed.
418A value of t means to show all source files."
419  :group 'idlwave-routine-info
420  :type 'integer)
421
422(defcustom idlwave-library-path nil
423  "Library path for Windows and Mac OS (OS9).  Not needed under UNIX.
424When selecting the directories to scan for IDL user catalog routine
425info, IDLWAVE can, under UNIX, query the shell for the exact search
426path (the value of !PATH).  However, under MS-Windows, the
427IDLWAVE shell does not work.  In this case, this variable can be
428set to specify the paths where IDLWAVE can find PRO files.  The
429shell will only be asked for a list of paths when this variable
430is nil.  The value is a list of directories.  A directory
431preceded by a `+' will be searched recursively.  If you set this
432variable on a UNIX system, the shell will not be queried.  See
433also `idlwave-system-directory'."
434  :group 'idlwave-routine-info
435  :type '(repeat (directory)))
436
437(defcustom idlwave-system-directory ""
438  "The IDL system directory for Windows and Mac OS.  Not needed under
439UNIX.  Set this to the value of the `!DIR' system variable in IDL.
440IDLWAVE uses this to find out which of the library routines belong to
441the official system library.  All files inside the `lib' subdirectory
442are considered system library files - so don't install private stuff
443in this directory.  On UNIX systems, IDLWAVE queries the shell for the
444value of `!DIR'.  See also `idlwave-library-path'."
445  :group 'idlwave-routine-info
446  :type 'directory)
447
448;; Configuration files
449(defcustom idlwave-config-directory
450  (locate-user-emacs-file "idlwave" ".idlwave")
451  "Directory for configuration files and user-library catalog."
452  :version "24.4"			; added locate-user-emacs-file
453  :group 'idlwave-routine-info
454  :type 'file)
455
456(defvar idlwave-user-catalog-file "idlusercat.el")
457(defvar idlwave-xml-system-rinfo-converted-file "idl_xml_rinfo.el")
458(defvar idlwave-path-file "idlpath.el")
459
460(defcustom idlwave-special-lib-alist nil
461  "Alist of regular expressions matching special library directories.
462When listing routine source locations, IDLWAVE gives a short hint where
463the file defining the routine is located.  By default it lists `SystemLib'
464for routines in the system library `!DIR/lib' and `Library' for anything
465else.  This variable can define additional types.  The car of each entry
466is a regular expression matching the file name (they normally will match
467on the path).  The cdr is the string to be used as identifier.  Max 10
468chars are allowed."
469  :group 'idlwave-routine-info
470  :type '(repeat
471	  (cons regexp string)))
472
473(defcustom idlwave-auto-write-paths t
474  "Write out path (!PATH) and system directory (!DIR) info automatically.
475Path info is needed to locate library catalog files.  If non-nil,
476whenever the path-list changes as a result of shell-query, etc., it is
477written to file.  Otherwise, the menu option \"Write Paths\" can be
478used to force a write."
479  :group 'idlwave-routine-info
480  :type 'boolean)
481
482(defgroup idlwave-completion nil
483  "Completion options for IDLWAVE mode."
484  :prefix "idlwave"
485  :group 'idlwave)
486
487(eval-and-compile
488  (defconst idlwave-tmp
489    '(choice :tag "by applying the function"
490      (const upcase)
491      (const downcase)
492      (const capitalize)
493      (const preserve)
494      (symbol :tag "Other"))))
495
496(defcustom idlwave-completion-case '((routine . upcase)
497				     (keyword . upcase)
498				     (class   . preserve)
499				     (method  . preserve))
500  "Association list setting the case of completed words.
501
502This variable determines the case (UPPER/lower/Capitalized...) of
503words inserted into the buffer by completion.  The preferred case can
504be specified separately for routine names, keywords, classes and
505methods.
506This alist should therefore have entries for `routine' (normal
507functions and procedures, i.e. non-methods), `keyword', `class', and
508`method'.  Plausible values are
509
510upcase      upcase whole word, like `BOX_CURSOR'
511downcase    downcase whole word, like `read_ppm'
512capitalize  capitalize each part, like `Widget_Control'
513preserve    preserve case as is, like `IDLgrView'
514
515The value can also be any Emacs Lisp function which transforms the
516case of characters in a string.
517
518A value of `preserve' means that the case of the completed word is
519identical to the way it was written in the definition statement of the
520routine.  This was implemented to allow for mixed-case completion, in
521particular of object classes and methods.
522If a completable word is defined in multiple locations, the meaning of
523`preserve' is not unique since the different definitions might be
524cased differently.  Therefore IDLWAVE always takes the case of the
525*first* definition it encounters during routine info collection and
526uses the case derived from it consistently.
527
528Note that a lowercase-only string in the buffer will always be completed in
529lower case (but see the variable `idlwave-completion-force-default-case').
530
531After changing this variable, you need to either restart Emacs or press
532`C-u C-c C-i' to update the internal lists."
533  :group 'idlwave-completion
534  :type `(repeat
535	  (cons (symbol :tag "Derive completion case for")
536		,idlwave-tmp)))
537
538(defcustom idlwave-completion-force-default-case nil
539  "Non-nil means, completion will always honor `idlwave-completion-case'.
540When nil, only the completion of a mixed case or upper case string
541will honor the default settings in `idlwave-completion-case', while
542the completion of lower case strings will be completed entirely in
543lower case."
544  :group 'idlwave-completion
545  :type 'boolean)
546
547(defcustom idlwave-complete-empty-string-as-lower-case nil
548  "Non-nil means, the empty string is considered downcase for completion.
549The case of what is already in the buffer determines the case of completions.
550When this variable is non-nil, the empty string is considered to be downcase.
551Completing on the empty string then offers downcase versions of the possible
552completions."
553  :group 'idlwave-completion
554  :type 'boolean)
555
556(defcustom idlwave-buffer-case-takes-precedence nil
557  "Non-nil means, the case of tokens in buffers dominates over system stuff.
558To make this possible, we need to re-case everything each time we update
559the routine info from the buffers.  This is slow.
560The default is to consider the case given in the system and library files
561first which makes updating much faster."
562  :group 'idlwave-completion
563  :type 'boolean)
564
565(defcustom idlwave-highlight-help-links-in-completion t
566  "Non-nil means, highlight completions for which system help is available.
567Help can then be accessed with mouse-3.
568This option is only effective when the online help system is installed."
569  :group 'idlwave-completion
570  :type 'boolean)
571
572(defcustom idlwave-support-inheritance t
573  "Non-nil means, treat inheritance with completion, online help etc.
574When nil, IDLWAVE only knows about the native methods and tags of a class,
575not about inherited ones."
576  :group 'idlwave-routine-info
577  :type 'boolean)
578
579(defcustom idlwave-keyword-class-inheritance '("^[gs]etproperty$" "^init$")
580  "List of regular expressions for class-driven keyword inheritance.
581Keyword inheritance is often tied to class inheritance by \"chaining\"
582up the class tree.  While it cannot be assumed that the presence of an
583_EXTRA or _REF_EXTRA symbol guarantees such chaining will occur, for
584certain methods this assumption is almost always true.  The methods
585for which to assume this can be set here."
586  :group 'idlwave-routine-info
587  :type '(repeat (regexp :tag "Match method:")))
588
589
590(defcustom idlwave-completion-show-classes 1
591  "Number of classes to show when completing object methods and keywords.
592When completing methods or keywords for an object with unknown class,
593the *Completions* buffer will show the valid classes for each completion
594like this:
595
596MyMethod <Class1,Class2,Class3>
597
598The value of this variable may be nil to inhibit display, or an integer to
599indicate the maximum number of classes to display.
600
601On XEmacs, a full list of classes will also be placed into a `help-echo'
602property on the completion items, so that the list of classes for the current
603item is displayed in the echo area.  If the value of this variable is a
604negative integer, the `help-echo' property will be suppressed."
605  :group 'idlwave-completion
606  :type '(choice (const :tag "Don't show" nil)
607		 (integer :tag "Number of classes shown" 1)))
608
609(defcustom idlwave-completion-fontify-classes t
610  "Non-nil means, fontify the classes in completions buffer.
611This makes it easier to distinguish the completion items from the extra
612class info listed.  See `idlwave-completion-show-classes'."
613  :group 'idlwave-completion
614  :type 'boolean)
615
616(defcustom idlwave-query-class '((method-default . nil)
617				 (keyword-default . nil))
618  "Association list governing specification of object classes for completion.
619
620When IDLWAVE tries to complete object-oriented methods, it usually
621cannot determine the class of a given object from context.  In order
622to provide the user with a correct list of methods or keywords, it
623needs to determine the appropriate class.  IDLWAVE has two ways of
624doing this (well, three ways if you count the shell... see
625`idlwave-shell-query-for-class'):
626
6271. Combine the items of all available classes which contain this
628   method for the purpose of completion.  So when completing a method,
629   all methods of all known classes are available, and when completing
630   a keyword, all keywords allowed for this method in any class are
631   shown.  This behavior is very much like normal completion and is
632   therefore the default.  It works much better than one might think -
633   only for the INIT, GETPROPERTY and SETPROPERTY the keyword lists
634   become uncomfortably long.  See also
635   `idlwave-completion-show-classes'.
636
6372. The second possibility is to ask the user on each occasion.  To
638   make this less interruptive, IDLWAVE can store the class as a text
639   property on the object operator `->'.  For a given object in the
640   source code, class selection will then be needed only once
641   - for example to complete the method.  Keywords to the method can
642   then be completed directly, because the class is already known.
643   You will have to turn on the storage of the selected class
644   explicitly with the variable `idlwave-store-inquired-class'.
645
646This variable allows you to configure IDLWAVE's method and
647method-keyword completion behavior.  Its value is an alist, which
648should contain at least two elements: (method-default . VALUE) and
649\(keyword-default . VALUE), where VALUE is either t or nil.  These
650specify if the class should be found during method and keyword
651completion, respectively.
652
653The alist may have additional entries specifying exceptions from the
654keyword completion rule for specific methods, like INIT or
655GETPROPERTY.  In order to turn on class specification for the INIT
656method, add an entry (\"INIT\" . t).  The method name must be ALL-CAPS."
657  :group 'idlwave-completion
658  :type '(list
659	  (cons (const method-default)
660		(boolean :tag "Determine class when completing METHODS    "))
661	  (cons (const keyword-default)
662		(boolean :tag "Determine class when completing KEYWORDS   "))
663	  (repeat
664	   :tag "Exceptions to defaults"
665	   :inline t
666	   (cons (string  :tag "MODULE" :value "")
667		 (boolean :tag "Determine class for this method")))))
668
669(defcustom idlwave-store-inquired-class t
670  "Non-nil means, store class of a method call as text property on `->'.
671IDLWAVE sometimes has to ask the user for the class associated with a
672particular object method call.  This happens during the commands
673`idlwave-routine-info' and `idlwave-complete', depending upon the
674value of the variable `idlwave-query-class'.
675
676When you specify a class, this information can be stored as a text
677property on the `->' arrow in the source code, so that during the same
678editing session, IDLWAVE will not have to ask again.  When this
679variable is non-nil, IDLWAVE will store and reuse the class information.
680The class stored can be checked and removed with `\\[idlwave-routine-info]'
681on the arrow.
682
683The default of this variable is nil, since the result of commands then
684is more predictable.  However, if you know what you are doing, it can
685be nice to turn this on.
686
687An arrow which knows the class will be highlighted with
688`idlwave-class-arrow-face'.  The command \\[idlwave-routine-info]
689displays (with prefix arg: deletes) the class stored on the arrow
690at point."
691  :group 'idlwave-completion
692  :type 'boolean)
693
694(defcustom idlwave-class-arrow-face 'bold
695  "Face to highlight object operator arrows `->' which carry a class property.
696When IDLWAVE stores a class name as text property on an object arrow
697\(see variable `idlwave-store-inquired-class', it highlights the arrow
698with this font in order to remind the user that this arrow is special."
699  :group 'idlwave-completion
700  :type 'symbol)
701
702(defcustom idlwave-resize-routine-help-window t
703  "Non-nil means, resize the Routine-info *Help* window to fit the content."
704  :group 'idlwave-completion
705  :type 'boolean)
706
707(defcustom idlwave-keyword-completion-adds-equal t
708  "Non-nil means, completion automatically adds `=' after completed keywords."
709  :group 'idlwave-completion
710  :type 'boolean)
711
712(defcustom idlwave-function-completion-adds-paren t
713  "Non-nil means, completion automatically adds `(' after completed function.
714nil means, don't add anything.
715A value of `2' means, also add the closing parenthesis and position cursor
716between the two."
717  :group 'idlwave-completion
718  :type '(choice (const :tag "Nothing" nil)
719		 (const :tag "(" t)
720		 (const :tag "()" 2)))
721
722(defcustom idlwave-completion-restore-window-configuration t
723  "Non-nil means, try to restore the window configuration after completion.
724When completion is not unique, Emacs displays a list of completions.
725This messes up your window configuration.  With this variable set, IDLWAVE
726restores the old configuration after successful completion."
727  :group 'idlwave-completion
728  :type 'boolean)
729
730;;; Variables for abbrev and action behavior -----------------------------
731
732(defgroup idlwave-abbrev-and-indent-action nil
733  "IDLWAVE performs actions when expanding abbreviations or indenting lines.
734The variables in this group govern this."
735  :group 'idlwave)
736
737(defcustom idlwave-do-actions nil
738  "Non-nil means performs actions when indenting.
739The actions that can be performed are listed in `idlwave-indent-action-table'."
740  :group 'idlwave-abbrev-and-indent-action
741  :type 'boolean)
742
743(defcustom idlwave-abbrev-start-char "\\"
744  "A single character string used to start abbreviations in abbrev mode.
745Possible characters to choose from: ~\\=`%
746or even `?'.  `.' is not a good choice because it can make structure
747field names act like abbrevs in certain circumstances.
748
749Changes to this in `idlwave-mode-hook' will have no effect.  Instead a user
750must set it directly using `setq' in the init file before idlwave.el
751is loaded."
752  :group 'idlwave-abbrev-and-indent-action
753  :type 'string)
754
755(defcustom idlwave-surround-by-blank nil
756  "Non-nil means, enable `idlwave-surround'.
757If non-nil, `=',`<',`>',`&',`,', `->' are surrounded with spaces by
758`idlwave-surround'.
759See help for `idlwave-indent-action-table' for symbols using `idlwave-surround'.
760
761Also see the default key bindings for keys using `idlwave-surround'.
762Keys are bound and made into actions calling `idlwave-surround' with
763`idlwave-action-and-binding'.
764See help for `idlwave-action-and-binding' for examples.
765
766Also see help for `idlwave-surround'."
767  :group 'idlwave-abbrev-and-indent-action
768  :type 'boolean)
769
770(defcustom idlwave-pad-keyword t
771  "Non-nil means pad `=' in keywords (routine calls or defs) like assignment.
772Whenever `idlwave-surround' is non-nil then this affects how `=' is
773padded for keywords and for variables.  If t, pad the same as for
774assignments.  If nil then spaces are removed.  With any other value,
775spaces are left unchanged."
776  :group 'idlwave-abbrev-and-indent-action
777  :type '(choice
778	  (const :tag "Pad like assignments" t)
779	  (const :tag "Remove space near `='" nil)
780	  (other :tag "Keep space near `='" keep)))
781
782(defcustom idlwave-show-block t
783  "Non-nil means point blinks to block beginning for `idlwave-show-begin'."
784  :group 'idlwave-abbrev-and-indent-action
785  :type 'boolean)
786
787(defcustom idlwave-expand-generic-end nil
788  "Non-nil means expand generic END to ENDIF/ENDELSE/ENDWHILE etc."
789  :group 'idlwave-abbrev-and-indent-action
790  :type 'boolean)
791
792(defcustom idlwave-reindent-end t
793  "Non-nil means re-indent line after END was typed."
794  :group 'idlwave-abbrev-and-indent-action
795  :type 'boolean)
796
797(defcustom idlwave-abbrev-move t
798  "Non-nil means the abbrev hook can move point.
799Set to nil by `idlwave-expand-region-abbrevs'.  To see the abbrev
800definitions, use the command `list-abbrevs', for abbrevs that move
801point.  Moving point is useful, for example, to place point between
802parentheses of expanded functions.
803
804See `idlwave-check-abbrev'."
805  :group 'idlwave-abbrev-and-indent-action
806  :type 'boolean)
807
808(defcustom idlwave-abbrev-change-case nil
809  "Non-nil means all abbrevs will be forced to either upper or lower case.
810If the value t, all expanded abbrevs will be upper case.
811If the value is `down' then abbrevs will be forced to lower case.
812If nil, the case will not change.
813If `idlwave-reserved-word-upcase' is non-nil, reserved words will always be
814upper case, regardless of this variable."
815  :group 'idlwave-abbrev-and-indent-action
816  :type 'boolean)
817
818(defcustom idlwave-reserved-word-upcase nil
819  "Non-nil means, reserved words will be made upper case via abbrev expansion.
820If nil case of reserved words is controlled by `idlwave-abbrev-change-case'.
821Has effect only if in abbrev-mode."
822  :group 'idlwave-abbrev-and-indent-action
823  :type 'boolean)
824
825;;; Action/Expand Tables.
826;;
827;; The average user may have difficulty modifying this directly.  It
828;; can be modified/set in idlwave-mode-hook, but it is easier to use
829;; idlwave-action-and-binding. See help for idlwave-action-and-binding for
830;; examples of how to add an action.
831;;
832;; The action table is used by `idlwave-indent-line' whereas both the
833;; action and expand tables are used by `idlwave-indent-and-action'.  In
834;; general, the expand table is only used when a line is explicitly
835;; indented.  Whereas, in addition to being used when the expand table
836;; is used, the action table is used when a line is indirectly
837;; indented via line splitting, auto-filling or a new line creation.
838;;
839;; Example actions:
840;;
841;;  Capitalize system vars
842;;   (idlwave-action-and-binding idlwave-sysvar '(capitalize-word 1) t)
843;;
844;;  Capitalize procedure name
845;;   (idlwave-action-and-binding "\\<\\(pro\\|function\\)\\>[ \t]*\\<"
846;;                           '(capitalize-word 1) t)
847;;
848;;  Capitalize common block name
849;;   (idlwave-action-and-binding "\\<common\\>[ \t]+\\<"
850;;                           '(capitalize-word 1) t)
851;;  Capitalize label
852;;   (idlwave-action-and-binding (concat "^[ \t]*" idlwave-label)
853;;                           '(capitalize-word -1) t)
854
855(defvar idlwave-indent-action-table nil
856  "Associated array containing action lists of search string (car),
857and function as a cdr.  This table is used by `idlwave-indent-line'.
858See documentation for `idlwave-do-action' for a complete description of
859the action lists.
860
861Additions to the table are made with `idlwave-action-and-binding' when a
862binding is not requested.
863See help on `idlwave-action-and-binding' for examples.")
864
865(defvar idlwave-indent-expand-table nil
866  "Associated array containing action lists of search string (car),
867and function as a cdr.  The table is used by the
868`idlwave-indent-and-action' function.  See documentation for
869`idlwave-do-action' for a complete description of the action lists.
870
871Additions to the table are made with `idlwave-action-and-binding' when a
872binding is requested.
873See help on `idlwave-action-and-binding' for examples.")
874
875;;; Documentation header and history keyword ---------------------------------
876
877(defgroup idlwave-documentation nil
878  "Options for documenting IDLWAVE files."
879  :group 'idlwave)
880
881;; FIXME: make defcustom?
882(defvar idlwave-file-header
883  (list nil
884        ";+
885; NAME:
886;
887;
888;
889; PURPOSE:
890;
891;
892;
893; CATEGORY:
894;
895;
896;
897; CALLING SEQUENCE:
898;
899;
900;
901; INPUTS:
902;
903;
904;
905; OPTIONAL INPUTS:
906;
907;
908;
909; KEYWORD PARAMETERS:
910;
911;
912;
913; OUTPUTS:
914;
915;
916;
917; OPTIONAL OUTPUTS:
918;
919;
920;
921; COMMON BLOCKS:
922;
923;
924;
925; SIDE EFFECTS:
926;
927;
928;
929; RESTRICTIONS:
930;
931;
932;
933; PROCEDURE:
934;
935;
936;
937; EXAMPLE:
938;
939;
940;
941; MODIFICATION HISTORY:
942;
943;-
944")
945  "A list (PATHNAME STRING) specifying the doc-header template to use for
946summarizing a file.  If PATHNAME is non-nil then this file will be included.
947Otherwise STRING is used.  If nil, the file summary will be omitted.
948For example you might set PATHNAME to the path for the
949lib_template.pro file included in the IDL distribution.")
950
951(defcustom idlwave-header-to-beginning-of-file t
952  "Non-nil means, the documentation header will always be at start of file.
953When nil, the header is positioned between the PRO/FUNCTION line of
954the current routine and the code, allowing several routine headers in
955a file."
956  :group 'idlwave-documentation
957  :type 'boolean)
958
959(defcustom idlwave-timestamp-hook 'idlwave-default-insert-timestamp
960  "The hook function used to update the timestamp of a function."
961  :group 'idlwave-documentation
962  :type 'function)
963
964(defcustom idlwave-doc-modifications-keyword "HISTORY"
965  "The modifications keyword to use with the log documentation commands.
966A `:' is added to the keyword end.
967Inserted by doc-header and used to position logs by doc-modification.
968If nil it will not be inserted."
969  :group 'idlwave-documentation
970  :type 'string)
971
972(defcustom idlwave-doclib-start "^;+\\+"
973  "Regexp matching the start of a document library header."
974  :group 'idlwave-documentation
975  :type 'regexp)
976
977(defcustom idlwave-doclib-end "^;+-"
978  "Regexp matching the end of a document library header."
979  :group 'idlwave-documentation
980  :type 'regexp)
981
982;;; External Programs -------------------------------------------------------
983
984(defgroup idlwave-external-programs nil
985  "Path locations of external commands used by IDLWAVE."
986  :group 'idlwave)
987
988(defcustom idlwave-shell-explicit-file-name "idl"
989  "If non-nil, this is the command to run IDL.
990Should be an absolute file path or path relative to the current environment
991execution search path.  If you want to specify command line switches
992for the IDL program, use `idlwave-shell-command-line-options'.
993
994I know the name of this variable is badly chosen, but I cannot change
995it without compromising backwards-compatibility."
996  :group 'idlwave-external-programs
997  :type 'string)
998
999(defcustom idlwave-shell-command-line-options nil
1000  "A list of command line options for calling the IDL program.
1001Since IDL is executed directly without going through a shell like /bin/sh,
1002this should be a list of strings like (\"-rt=file\" \"-nw\") with a separate
1003string for each argument.  But you may also give a single string which
1004contains the options whitespace-separated.  Emacs will be kind enough to
1005split it for you."
1006  :type '(choice
1007	  string
1008	  (repeat (string :value "")))
1009  :group 'idlwave-external-programs)
1010
1011(defcustom idlwave-help-application "idlhelp"
1012  "The external application providing reference help for programming.
1013Obsolete, if the IDL Assistant is being used for help."
1014  :group 'idlwave-external-programs
1015  :type 'string)
1016
1017;;; Some Shell variables which must be defined here.-----------------------
1018
1019(defcustom idlwave-shell-debug-modifiers '()
1020  "List of modifiers to be used for the debugging commands.
1021Will be used to bind debugging commands in the shell buffer and in all
1022source buffers.  These are additional convenience bindings, the debugging
1023commands are always available with the `C-c C-d' prefix.
1024If you set this to (control shift), this means setting a breakpoint will
1025be on `C-S-b', compiling a source file on `C-S-c' etc.  Possible modifiers
1026are `control', `meta', `super', `hyper', `alt', and `shift'."
1027  :group 'idlwave-shell-general-setup
1028  :type '(set :tag "Specify modifiers"
1029	       (const control)
1030	       (const meta)
1031	       (const super)
1032	       (const hyper)
1033	       (const alt)
1034	       (const shift)))
1035
1036(defcustom idlwave-shell-automatic-start nil
1037  "If non-nil attempt invoke `idlwave-shell' if not already running.
1038This is checked when an attempt to send a command to an
1039IDL process is made."
1040  :group 'idlwave-shell-general-setup
1041  :type 'boolean)
1042
1043;;; Miscellaneous variables -------------------------------------------------
1044
1045(defgroup idlwave-misc nil
1046  "Miscellaneous options for IDLWAVE mode."
1047  :link '(custom-group-link :tag "Font Lock Faces group" font-lock-faces)
1048  :group 'idlwave)
1049
1050(defcustom idlwave-startup-message t
1051  "Non-nil displays a startup message when `idlwave-mode' is first called."
1052  :group 'idlwave-misc
1053  :type 'boolean)
1054
1055(defcustom idlwave-default-font-lock-items
1056  '(pros-and-functions batch-files idlwave-idl-keywords label goto
1057		       common-blocks class-arrows)
1058  "Items which should be fontified on the default fontification level 2.
1059IDLWAVE defines 3 levels of fontification.  Level 1 is very little, level 3
1060is everything and level 2 is specified by this list.
1061This variable must be set before IDLWAVE gets loaded.
1062It is a list of symbols; the following symbols are allowed:
1063
1064pros-and-functions   Procedure and Function definitions
1065batch-files          Batch Files
1066idlwave-idl-keywords IDL Keywords
1067label                Statement Labels
1068goto                 Goto Statements
1069common-blocks        Common Blocks
1070keyword-parameters   Keyword Parameters in routine definitions and calls
1071system-variables     System Variables
1072fixme                FIXME: Warning in comments (on XEmacs only v. 21.0 and up)
1073class-arrows         Object Arrows with class property"
1074  :group 'idlwave-misc
1075  :type '(set
1076	  :inline t :greedy t
1077	  (const :tag "Procedure and Function definitions" pros-and-functions)
1078	  (const :tag "Batch Files"                       batch-files)
1079	  (const :tag "IDL Keywords (reserved words)"     idlwave-idl-keywords)
1080	  (const :tag "Statement Labels"                  label)
1081	  (const :tag "Goto Statements"                   goto)
1082	  (const :tag "Tags in Structure Definition"      structtag)
1083	  (const :tag "Structure Name"                    structname)
1084	  (const :tag "Common Blocks"                     common-blocks)
1085	  (const :tag "Keyword Parameters"                keyword-parameters)
1086	  (const :tag "System Variables"                  system-variables)
1087	  (const :tag "FIXME: Warning"                    fixme)
1088	  (const :tag "Object Arrows with class property " class-arrows)))
1089
1090(defcustom idlwave-mode-hook nil
1091  "Normal hook.  Executed when a buffer is put into `idlwave-mode'."
1092  :group 'idlwave-misc
1093  :type 'hook)
1094
1095(defcustom idlwave-load-hook nil
1096  "Normal hook.  Executed when idlwave.el is loaded."
1097  :group 'idlwave-misc
1098  :type 'hook)
1099
1100(defvar idlwave-experimental nil
1101  "Non-nil means turn on a few experimental features.
1102This variable is only for the maintainer, to test difficult stuff,
1103while still distributing stable releases.
1104As a user, you should not set this to t.")
1105
1106;;;
1107;;; End customization variables section
1108;;;
1109
1110;;; Non customization variables
1111
1112;;; font-lock mode - Additions by Phil Williams, Ulrik Dickow and
1113;;; Simon Marshall <simon_at_gnu.ai.mit.edu>
1114;;; and Carsten Dominik...
1115
1116;; The following are the reserved words in IDL.  Maybe we should
1117;; highlight some more stuff as well?
1118;; Procedure declarations.  Fontify keyword plus procedure name.
1119(defvar idlwave-idl-keywords
1120  ;; To update this regexp, update the list of keywords and
1121  ;; evaluate the form.
1122  ;;	(insert
1123  ;;	 (prin1-to-string
1124  ;;	  (concat
1125  ;;	   "\\<\\("
1126  ;;	   (regexp-opt
1127  ;;	    '("||" "&&" "and" "or" "xor" "not"
1128  ;;	      "eq" "ge" "gt" "le" "lt" "ne"
1129  ;;	      "for" "do" "endfor"
1130  ;;	      "if" "then" "endif" "else" "endelse"
1131  ;;	      "case" "of" "endcase"
1132  ;;	      "switch" "break" "continue" "endswitch"
1133  ;;	      "begin" "end"
1134  ;;	      "repeat" "until" "endrep"
1135  ;;	      "while" "endwhile"
1136  ;;	      "goto" "return"
1137  ;;	      "inherits" "mod"
1138  ;;	      "compile_opt" "forward_function"
1139  ;;	      "on_error" "on_ioerror"))  ; on_error is not officially reserved
1140  ;;	   "\\)\\>")))
1141  "\\<\\(&&\\|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\\|||\\)\\>")
1142
1143
1144(let* (;; Procedure declarations.  Fontify keyword plus procedure name.
1145       ;; Function  declarations.  Fontify keyword plus function  name.
1146       (pros-and-functions
1147	'("\\<\\(function\\|pro\\)\\>[ \t]+\\(\\sw+\\(::\\sw+\\)?\\)"
1148	  (1 font-lock-keyword-face)
1149	  (2 font-lock-function-name-face nil t)))
1150
1151       ;; Common blocks
1152       (common-blocks
1153	'("\\<\\(common\\)\\>[ \t]*\\(\\sw+\\)?[ \t]*,?"
1154	  (1 font-lock-keyword-face)	          ; "common"
1155	  (2 font-lock-constant-face nil t)      ; block name
1156	  ("[ \t]*\\(\\sw+\\)[ ,]*"
1157	   ;; Start with point after block name and comma
1158	   (goto-char (match-end 0))  ; needed for XEmacs, could be nil
1159	   nil
1160	   (1 font-lock-variable-name-face)       ; variable names
1161	   )))
1162
1163       ;; Batch files
1164       (batch-files
1165	'("^[ \t]*\\(@[^ \t\n]+\\)" (1 font-lock-string-face)))
1166
1167       ;; FIXME warning.
1168       (fixme
1169	'("\\<FIXME:" (0 font-lock-warning-face t)))
1170
1171       ;; Labels
1172       (label
1173	'("^[ \t]*\\([a-zA-Z]\\sw*:\\)" (1 font-lock-constant-face)))
1174
1175       ;; The goto statement and its label
1176       (goto
1177	'("\\(goto\\)[ \t]*,[ \t]*\\([a-zA-Z]\\sw*\\)"
1178	  (1 font-lock-keyword-face)
1179	  (2 font-lock-constant-face)))
1180
1181       ;; Tags in structure definitions.  Note that this definition
1182       ;; actually collides with labels, so we have to use the same
1183       ;; face.  It also matches named subscript ranges,
1184       ;; e.g. vec{bottom:top].  No good way around this.
1185       (structtag
1186	'("\\<\\([a-zA-Z][a-zA-Z0-9_]*:\\)[^:]" (1 font-lock-constant-face)))
1187
1188       ;; Structure names
1189       (structname
1190	'("\\({\\|\\<inherits\\s-\\)\\s-*\\([a-zA-Z][a-zA-Z0-9_]*\\)[},\t \n]"
1191	  (2 font-lock-function-name-face)))
1192
1193       ;; Keyword parameters, like /xlog or ,xrange=[]
1194       ;; This is anchored to the comma preceding the keyword.
1195       ;; Treats continuation lines, works only during whole buffer
1196       ;; fontification.  Slow, use it only in fancy fontification.
1197       (keyword-parameters
1198	'("\\(,\\|[a-zA-Z0-9_](\\)[ \t]*\\(\\$[ \t]*\\(;.*\\)?\n\\([ \t]*\\(;.*\\)?\n\\)*[ \t]*\\)?\\(/[a-zA-Z_]\\sw*\\|[a-zA-Z_]\\sw*[ \t]*=\\)"
1199	  (6 font-lock-constant-face)))
1200
1201       ;; System variables start with a bang.
1202       (system-variables
1203	'("\\(![a-zA-Z_0-9]+\\(\\.\\sw+\\)?\\)"
1204	  (1 font-lock-variable-name-face)))
1205
1206       ;; Special and unusual operators (not used because too noisy)
1207       ;; (special-operators
1208       ;;  '("[<>#]" (0 font-lock-keyword-face)))
1209
1210       ;; All operators (not used because too noisy)
1211       ;; (all-operators
1212       ;;  '("[-*^#+<>/]" (0 font-lock-keyword-face)))
1213
1214       ;; Arrows with text property `idlwave-class'
1215       (class-arrows
1216	'(idlwave-match-class-arrows (0 idlwave-class-arrow-face))))
1217
1218  (defconst idlwave-font-lock-keywords-1
1219    (list pros-and-functions batch-files)
1220    "Subdued level highlighting for IDLWAVE mode.")
1221
1222  (defconst idlwave-font-lock-keywords-2
1223    (mapcar 'symbol-value idlwave-default-font-lock-items)
1224    "Medium level highlighting for IDLWAVE mode.")
1225
1226  (defconst idlwave-font-lock-keywords-3
1227	(list pros-and-functions
1228	      batch-files
1229	      idlwave-idl-keywords
1230	      label goto
1231	      structtag
1232	      structname
1233	      common-blocks
1234	      keyword-parameters
1235	      system-variables
1236	  class-arrows)
1237    "Gaudy level highlighting for IDLWAVE mode."))
1238
1239(defun idlwave-match-class-arrows (limit)
1240  ;; Match an object arrow with class property
1241  (and idlwave-store-inquired-class
1242       (re-search-forward "->" limit 'limit)
1243       (get-text-property (match-beginning 0) 'idlwave-class)))
1244
1245(defvar idlwave-font-lock-keywords idlwave-font-lock-keywords-2
1246  "Default expressions to highlight in IDLWAVE mode.")
1247
1248(defvar idlwave-font-lock-defaults
1249  '((idlwave-font-lock-keywords
1250     idlwave-font-lock-keywords-1
1251     idlwave-font-lock-keywords-2
1252     idlwave-font-lock-keywords-3)
1253    nil t
1254    ((?$ . "w") (?_ . "w") (?. . "w") (?| . "w") (?& . "w"))
1255    beginning-of-line))
1256
1257(put 'idlwave-mode 'font-lock-defaults
1258     idlwave-font-lock-defaults) ; XEmacs
1259
1260(defconst idlwave-comment-line-start-skip "^[ \t]*;"
1261  "Regexp to match the start of a full-line comment.
1262That is the _beginning_ of a line containing a comment delimiter `;' preceded
1263only by whitespace.")
1264
1265(defconst idlwave-begin-block-reg
1266  "\\<\\(pro\\|function\\|begin\\|case\\|switch\\)\\>"
1267  "Regular expression to find the beginning of a block.
1268The case does not matter.  The search skips matches in comments.")
1269
1270(defconst idlwave-begin-unit-reg "^\\s-*\\(pro\\|function\\)\\>\\|\\`"
1271  "Regular expression to find the beginning of a unit.
1272The case does not matter.")
1273
1274(defconst idlwave-end-unit-reg "^\\s-*\\(pro\\|function\\)\\>\\|\\'"
1275  "Regular expression to find the line that indicates the end of unit.
1276This line is the end of buffer or the start of another unit.
1277The case does not matter.  The search skips matches in comments.")
1278
1279(defconst idlwave-continue-line-reg "\\<\\$"
1280  "Regular expression to match a continued line.")
1281
1282(defconst idlwave-end-block-reg
1283  "\\<end\\(\\|case\\|switch\\|else\\|for\\|if\\|rep\\|while\\)\\>"
1284  "Regular expression to find the end of a block.
1285The case does not matter.  The search skips matches in comments.")
1286
1287(defconst idlwave-block-matches
1288  '(("pro"      . "end")
1289    ("function" . "end")
1290    ("case"     . "endcase")
1291    ("else"     . "endelse")
1292    ("for"      . "endfor")
1293    ("then"     . "endif")
1294    ("repeat"   . "endrep")
1295    ("switch"   . "endswitch")
1296    ("while"    . "endwhile"))
1297  "Matches between statements and the corresponding END variant.
1298The cars are the reserved words starting a block.  If the block really
1299begins with BEGIN, the cars are the reserved words before the begin
1300which can be used to identify the block type.
1301This is used to check for the correct END type, to close blocks and
1302to expand generic end statements to their detailed form.")
1303
1304(defconst idlwave-block-match-regexp
1305  "\\<\\(else\\|for\\|then\\|repeat\\|while\\)\\>"
1306"Regular expression matching reserved words which can stand before
1307blocks starting with a BEGIN statement.  The matches must have associations
1308`idlwave-block-matches'.")
1309
1310(defconst idlwave-identifier "[a-zA-Z_][a-zA-Z0-9$_]*"
1311  "Regular expression matching an IDL identifier.")
1312
1313(defconst idlwave-sysvar (concat "!" idlwave-identifier)
1314  "Regular expression matching IDL system variables.")
1315
1316(defconst idlwave-variable (concat idlwave-identifier "\\|" idlwave-sysvar)
1317  "Regular expression matching IDL variable names.")
1318
1319(defconst idlwave-label (concat idlwave-identifier ":")
1320  "Regular expression matching IDL labels.")
1321
1322(defconst idlwave-method-call (concat idlwave-identifier  "\\s *->"
1323				      "\\(\\s *" idlwave-identifier "::\\)?"
1324))
1325
1326(defconst idlwave-statement-match
1327  (list
1328   ;; "endif else" is the only possible "end" that can be
1329   ;; followed by a statement on the same line.
1330   '(endelse . ("end\\(\\|if\\)\\s +else" "end\\(\\|if\\)\\s +else"))
1331   ;; all other "end"s can not be followed by a statement.
1332   (cons 'end (list idlwave-end-block-reg nil))
1333   '(if . ("if\\>" "then"))
1334   '(for . ("for\\>" "do"))
1335   '(begin . ("begin\\>" nil))
1336   '(pdef . ("pro\\>\\|function\\>" nil))
1337   '(while . ("while\\>" "do"))
1338   '(repeat . ("repeat\\>" "repeat"))
1339   '(goto . ("goto\\>" nil))
1340   '(case . ("case\\>" nil))
1341   '(switch . ("switch\\>" nil))
1342   (cons 'call (list (concat "\\(" idlwave-variable "\\) *= *"
1343			     "\\(" idlwave-method-call "\\s *\\)?"
1344			     idlwave-identifier
1345			     "\\s *(") nil))
1346   (cons 'call (list (concat
1347		      "\\(" idlwave-method-call "\\s *\\)?"
1348		      idlwave-identifier
1349		      "\\( *\\($\\|\\$\\)\\|\\s *,\\)") nil))
1350   (cons 'assign (list (concat
1351			"\\(" idlwave-variable "\\) *=") nil)))
1352
1353  "Associated list of statement matching regular expressions.
1354Each regular expression matches the start of an IDL statement.
1355The first element of each association is a symbol giving the statement
1356type.  The associated value is a list.  The first element of this list
1357is a regular expression matching the start of an IDL statement for
1358identifying the statement type.  The second element of this list is a
1359regular expression for finding a substatement for the type.  The
1360substatement starts after the end of the found match modulo
1361whitespace.  If it is nil then the statement has no substatement.  The
1362list order matters since matching an assignment statement exactly is
1363not possible without parsing.  Thus assignment statement become just
1364the leftover unidentified statements containing an equal sign.")
1365
1366;; FIXME: This var seems to only ever be set, but never actually used!
1367(defvar idlwave-fill-function 'auto-fill-function
1368  "IDL mode auto fill function.")
1369
1370(defvar idlwave-comment-indent-function 'comment-indent-function
1371  "IDL mode comment indent function.")
1372
1373;; Note that this is documented in the v18 manuals as being a string
1374;; of length one rather than a single character.
1375;; The code in this file accepts either format for compatibility.
1376(defvar idlwave-comment-indent-char ?\
1377  "Character to be inserted for IDL comment indentation.
1378Normally a space.")
1379
1380(defconst idlwave-continuation-char ?$
1381  "Character which is inserted as a last character on previous line by
1382   \\[idlwave-split-line] to begin a continuation line.  Normally $.")
1383
1384(defconst idlwave-mode-version "6.1_em22")
1385
1386(defmacro idlwave-keyword-abbrev (&rest args)
1387  "Creates a function for abbrev hooks to call `idlwave-check-abbrev' with args."
1388  `(quote (lambda ()
1389	    ,(append '(idlwave-check-abbrev) args))))
1390
1391;; If I take the time I can replace idlwave-keyword-abbrev with
1392;; idlwave-code-abbrev and remove the quoted abbrev check from
1393;; idlwave-check-abbrev.  Then, e.g, (idlwave-keyword-abbrev 0 t) becomes
1394;; (idlwave-code-abbrev idlwave-check-abbrev 0 t).  In fact I should change
1395;; the name of idlwave-check-abbrev to something like idlwave-modify-abbrev.
1396
1397(defmacro idlwave-code-abbrev (&rest args)
1398  "Creates a function for abbrev hooks that ensures abbrevs are not quoted.
1399Specifically, if the abbrev is in a comment or string it is unexpanded.
1400Otherwise ARGS forms a list that is evaluated."
1401  ;; FIXME: it would probably be better to rely on the new :enable-function
1402  ;; to enforce the "don't expand in comments or strings".
1403  `(lambda ()
1404     ,(prin1-to-string args)  ;; Puts the code in the doc string
1405     (if (idlwave-quoted)
1406         (progn (unexpand-abbrev) nil)
1407       ,(append args))))
1408
1409(autoload 'idlwave-shell "idlw-shell"
1410  "Run an inferior IDL, with I/O through buffer `(idlwave-shell-buffer)'." t)
1411(autoload 'idlwave-shell-send-command "idlw-shell")
1412(autoload 'idlwave-shell-recenter-shell-window "idlw-shell"
1413  "Run `idlwave-shell' and switch back to current window" t)
1414(autoload 'idlwave-shell-save-and-run "idlw-shell"
1415  "Save and run buffer under the shell." t)
1416(autoload 'idlwave-shell-break-here "idlw-shell"
1417  "Set breakpoint in current line." t)
1418(autoload 'idlwave-shell-run-region "idlw-shell"
1419  "Compile and run the region." t)
1420
1421(fset 'idlwave-debug-map (make-sparse-keymap))
1422
1423(defvar idlwave-mode-map
1424  (let ((map (make-sparse-keymap)))
1425    (define-key map "\C-c "    'idlwave-hard-tab)
1426    (define-key map [(control tab)] 'idlwave-hard-tab)
1427    ;;(define-key map "\C-c\C- " 'idlwave-hard-tab)
1428    (define-key map "'"        'idlwave-show-matching-quote)
1429    (define-key map "\""       'idlwave-show-matching-quote)
1430    (define-key map "\C-g"     'idlwave-keyboard-quit)
1431    (define-key map "\C-c;"    'idlwave-toggle-comment-region)
1432    (define-key map "\C-\M-a"  'idlwave-beginning-of-subprogram)
1433    (define-key map "\C-\M-e"  'idlwave-end-of-subprogram)
1434    (define-key map "\C-c{"    'idlwave-beginning-of-block)
1435    (define-key map "\C-c}"    'idlwave-end-of-block)
1436    (define-key map "\C-c]"    'idlwave-close-block)
1437    (define-key map [(meta control h)] 'idlwave-mark-subprogram)
1438    (define-key map "\M-\C-n"  'idlwave-forward-block)
1439    (define-key map "\M-\C-p"  'idlwave-backward-block)
1440    (define-key map "\M-\C-d"  'idlwave-down-block)
1441    (define-key map "\M-\C-u"  'idlwave-backward-up-block)
1442    (define-key map "\M-\r"    'idlwave-split-line)
1443    (define-key map "\M-\C-q"  'idlwave-indent-subprogram)
1444    (define-key map "\C-c\C-p" 'idlwave-previous-statement)
1445    (define-key map "\C-c\C-n" 'idlwave-next-statement)
1446    ;; (define-key map "\r"       'idlwave-newline)
1447    ;; (define-key map "\t"       'idlwave-indent-line)
1448    (define-key map [(shift iso-lefttab)] 'idlwave-indent-statement)
1449    (define-key map "\C-c\C-a" 'idlwave-auto-fill-mode)
1450    (define-key map "\M-q"     'idlwave-fill-paragraph)
1451    (define-key map "\M-s"     'idlwave-edit-in-idlde)
1452    (define-key map "\C-c\C-h" 'idlwave-doc-header)
1453    (define-key map "\C-c\C-m" 'idlwave-doc-modification)
1454    (define-key map "\C-c\C-c" 'idlwave-case)
1455    (define-key map "\C-c\C-d" 'idlwave-debug-map)
1456    (when (and (listp idlwave-shell-debug-modifiers)
1457               (not (equal idlwave-shell-debug-modifiers '())))
1458      ;; Bind the debug commands also with the special modifiers.
1459      (let ((shift (memq 'shift idlwave-shell-debug-modifiers))
1460            (mods-noshift
1461             (delq 'shift (copy-sequence idlwave-shell-debug-modifiers))))
1462        (define-key map
1463          (vector (append mods-noshift (list (if shift ?C ?c))))
1464          'idlwave-shell-save-and-run)
1465        (define-key map
1466          (vector (append mods-noshift (list (if shift ?B ?b))))
1467          'idlwave-shell-break-here)
1468        (define-key map
1469          (vector (append mods-noshift (list (if shift ?E ?e))))
1470          'idlwave-shell-run-region)))
1471    (define-key map "\C-c\C-d\C-c" 'idlwave-shell-save-and-run)
1472    (define-key map "\C-c\C-d\C-b" 'idlwave-shell-break-here)
1473    (define-key map "\C-c\C-d\C-e" 'idlwave-shell-run-region)
1474    (define-key map "\C-c\C-f" 'idlwave-for)
1475    ;;  (define-key map "\C-c\C-f" 'idlwave-function)
1476    ;;  (define-key map "\C-c\C-p" 'idlwave-procedure)
1477    (define-key map "\C-c\C-r" 'idlwave-repeat)
1478    (define-key map "\C-c\C-w" 'idlwave-while)
1479    (define-key map "\C-c\C-k" 'idlwave-kill-autoloaded-buffers)
1480    (define-key map "\C-c\C-s" 'idlwave-shell)
1481    (define-key map "\C-c\C-l" 'idlwave-shell-recenter-shell-window)
1482    (define-key map "\C-c\C-b" 'idlwave-list-buffer-load-path-shadows)
1483    (define-key map "\C-c\C-v"   'idlwave-find-module)
1484    (define-key map "\C-c\C-t"   'idlwave-find-module-this-file)
1485    (define-key map "\C-c?"      'idlwave-routine-info)
1486    (define-key map "\M-?"       'idlwave-context-help)
1487    (define-key map [(control meta ?\?)]
1488      'idlwave-help-assistant-help-with-topic)
1489    ;; Pickup both forms of Esc/Meta binding
1490    (define-key map [(meta tab)] 'idlwave-complete)
1491    (define-key map [?\e?\t] 'idlwave-complete)
1492    (define-key map "\M-\C-i" 'idlwave-complete)
1493    (define-key map "\C-c\C-i" 'idlwave-update-routine-info)
1494    (define-key map "\C-c="    'idlwave-resolve)
1495    (define-key map
1496      (if (featurep 'xemacs) [(shift button3)] [(shift mouse-3)])
1497      'idlwave-mouse-context-help)
1498    map)
1499  "Keymap used in IDL mode.")
1500
1501(defvar idlwave-mode-syntax-table
1502  (let ((st (make-syntax-table)))
1503    (modify-syntax-entry ?+   "."  st)
1504    (modify-syntax-entry ?-   "."  st)
1505    (modify-syntax-entry ?*   "."  st)
1506    (modify-syntax-entry ?/   "."  st)
1507    (modify-syntax-entry ?^   "."  st)
1508    (modify-syntax-entry ?#   "."  st)
1509    (modify-syntax-entry ?=   "."  st)
1510    (modify-syntax-entry ?%   "."  st)
1511    (modify-syntax-entry ?<   "."  st)
1512    (modify-syntax-entry ?>   "."  st)
1513    (modify-syntax-entry ?\'  "\"" st)
1514    (modify-syntax-entry ?\"  "\"" st)
1515    (modify-syntax-entry ?\\  "."  st)
1516    (modify-syntax-entry ?_   "_"  st)
1517    (modify-syntax-entry ?{   "(}" st)
1518    (modify-syntax-entry ?}   "){" st)
1519    (modify-syntax-entry ?$   "_"  st)
1520    (modify-syntax-entry ?.   "."  st)
1521    (modify-syntax-entry ?\;  "<"  st)
1522    (modify-syntax-entry ?\n  ">"  st)
1523    (modify-syntax-entry ?\f  ">"  st)
1524    st)
1525  "Syntax table in use in `idlwave-mode' buffers.")
1526
1527(defvar idlwave-find-symbol-syntax-table
1528  (let ((st (copy-syntax-table idlwave-mode-syntax-table)))
1529    (modify-syntax-entry ?$   "w"  st)
1530    (modify-syntax-entry ?_   "w"  st)
1531    (modify-syntax-entry ?!   "w"  st)
1532    (modify-syntax-entry ?.   "w"  st)
1533    st)
1534  "Syntax table that treats symbol characters as word characters.")
1535
1536(defmacro idlwave-with-special-syntax (&rest body)
1537  "Execute BODY with a different syntax table."
1538  `(let ((saved-syntax (syntax-table)))
1539     (unwind-protect
1540	 (progn
1541	   (set-syntax-table idlwave-find-symbol-syntax-table)
1542	   ,@body)
1543       (set-syntax-table saved-syntax))))
1544
1545;(defmacro idlwave-with-special-syntax1 (&rest body)
1546;  "Execute BODY with a different syntax table."
1547;  `(let ((saved-syntax (syntax-table)))
1548;     (unwind-protect
1549;	  (progn
1550;	    (set-syntax-table idlwave-find-symbol-syntax-table)
1551;	    ,@body)
1552;	(set-syntax-table saved-syntax))))
1553
1554(defun idlwave-action-and-binding (key cmd &optional select)
1555  "KEY and CMD are made into a key binding and an indent action.
1556KEY is a string - same as for the `define-key' function.  CMD is a
1557function of no arguments or a list to be evaluated.  CMD is bound to
1558KEY in `idlwave-mode-map' by defining an anonymous function calling
1559`self-insert-command' followed by CMD.  If KEY contains more than one
1560character a binding will only be set if SELECT is `both'.
1561
1562\(KEY . CMD) is also placed in the `idlwave-indent-expand-table',
1563replacing any previous value for KEY.  If a binding is not set then it
1564will instead be placed in `idlwave-indent-action-table'.
1565
1566If the optional argument SELECT is nil then an action and binding are
1567created.  If SELECT is `noaction', then a binding is always set and no
1568action is created.  If SELECT is `both' then an action and binding
1569will both be created even if KEY contains more than one character.
1570Otherwise, if SELECT is non-nil then only an action is created.
1571
1572Some examples:
1573No spaces before and 1 after a comma
1574   (idlwave-action-and-binding \",\"  \\='(idlwave-surround 0 1))
1575A minimum of 1 space before and after `=' (see `idlwave-expand-equal').
1576   (idlwave-action-and-binding \"=\"  \\='(idlwave-expand-equal -1 -1))
1577Capitalize system variables - action only
1578   (idlwave-action-and-binding idlwave-sysvar \\='(capitalize-word 1) t)"
1579  (if (not (equal select 'noaction))
1580      ;; Add action
1581      (let* ((table (if select 'idlwave-indent-action-table
1582                      'idlwave-indent-expand-table))
1583	     (table-key (regexp-quote key))
1584             (cell (assoc table-key (eval table))))
1585        (if cell
1586            ;; Replace action command
1587            (setcdr cell cmd)
1588          ;; New action
1589          (set table (append (eval table) (list (cons table-key cmd)))))))
1590  ;; Make key binding for action
1591  (if (or (and (null select) (= (length key) 1))
1592          (equal select 'noaction)
1593          (equal select 'both))
1594      (define-key idlwave-mode-map key
1595        `(lambda ()
1596           (interactive)
1597           (self-insert-command 1)
1598           ,(if (listp cmd) cmd (list cmd))))))
1599
1600;; Set action and key bindings.
1601;; See description of the function `idlwave-action-and-binding'.
1602;; Automatically add spaces for the following characters
1603
1604;; Actions for & are complicated by &&
1605(idlwave-action-and-binding "&"  'idlwave-custom-ampersand-surround)
1606
1607;; Automatically add spaces to equal sign if not keyword.  This needs
1608;; to go ahead of > and <, so >= and <= will be treated correctly
1609(idlwave-action-and-binding "="  '(idlwave-expand-equal -1 -1))
1610
1611;; Actions for > and < are complicated by >=, <=, and ->...
1612(idlwave-action-and-binding "<"  '(idlwave-custom-ltgtr-surround nil))
1613(idlwave-action-and-binding ">"  '(idlwave-custom-ltgtr-surround 'gtr))
1614
1615(idlwave-action-and-binding ","  '(idlwave-surround 0 -1 1))
1616
1617
1618;;;
1619;;; Abbrev Section
1620;;;
1621;;; When expanding abbrevs and the abbrev hook moves backward, an extra
1622;;; space is inserted (this is the space typed by the user to expanded
1623;;; the abbrev).
1624;;;
1625(defvar idlwave-mode-abbrev-table nil
1626  "Abbreviation table used for IDLWAVE mode.")
1627(define-abbrev-table 'idlwave-mode-abbrev-table ())
1628
1629(defun idlwave-define-abbrev (name expansion hook &optional noprefix table)
1630  "Define-abbrev with backward compatibility.
1631
1632If NOPREFIX is non-nil, don't prepend prefix character.  Installs into
1633`idlwave-mode-abbrev-table' unless TABLE is non-nil."
1634  (let ((abbrevs-changed nil)  ;; mask the current value to avoid save
1635	(args (list (or table idlwave-mode-abbrev-table)
1636		    (if noprefix name (concat idlwave-abbrev-start-char name))
1637		    expansion
1638		    hook)))
1639    (condition-case nil
1640	(apply 'define-abbrev (append args '(0 t)))
1641      (error (apply 'define-abbrev args)))))
1642
1643(condition-case nil
1644    (modify-syntax-entry (string-to-char idlwave-abbrev-start-char)
1645			 "w" idlwave-mode-syntax-table)
1646  (error nil))
1647
1648;;
1649;; Templates
1650;;
1651(idlwave-define-abbrev "c"   "" (idlwave-code-abbrev idlwave-case))
1652(idlwave-define-abbrev "sw"  "" (idlwave-code-abbrev idlwave-switch))
1653(idlwave-define-abbrev "f"   "" (idlwave-code-abbrev idlwave-for))
1654(idlwave-define-abbrev "fu"  "" (idlwave-code-abbrev idlwave-function))
1655(idlwave-define-abbrev "pr"  "" (idlwave-code-abbrev idlwave-procedure))
1656(idlwave-define-abbrev "r"   "" (idlwave-code-abbrev idlwave-repeat))
1657(idlwave-define-abbrev "w"   "" (idlwave-code-abbrev idlwave-while))
1658(idlwave-define-abbrev "i"   "" (idlwave-code-abbrev idlwave-if))
1659(idlwave-define-abbrev "elif" "" (idlwave-code-abbrev idlwave-elif))
1660;;
1661;; Keywords, system functions, conversion routines
1662;;
1663(idlwave-define-abbrev "ap" "arg_present()" (idlwave-keyword-abbrev 1))
1664(idlwave-define-abbrev "b"  "begin"        (idlwave-keyword-abbrev 0 t))
1665(idlwave-define-abbrev "co" "common"       (idlwave-keyword-abbrev 0 t))
1666(idlwave-define-abbrev "cb" "byte()"       (idlwave-keyword-abbrev 1))
1667(idlwave-define-abbrev "cx" "fix()"        (idlwave-keyword-abbrev 1))
1668(idlwave-define-abbrev "cl" "long()"       (idlwave-keyword-abbrev 1))
1669(idlwave-define-abbrev "cf" "float()"      (idlwave-keyword-abbrev 1))
1670(idlwave-define-abbrev "cs" "string()"     (idlwave-keyword-abbrev 1))
1671(idlwave-define-abbrev "cc" "complex()"    (idlwave-keyword-abbrev 1))
1672(idlwave-define-abbrev "cd" "double()"     (idlwave-keyword-abbrev 1))
1673(idlwave-define-abbrev "e"  "else"         (idlwave-keyword-abbrev 0 t))
1674(idlwave-define-abbrev "ec" "endcase"      'idlwave-show-begin)
1675(idlwave-define-abbrev "es" "endswitch"    'idlwave-show-begin)
1676(idlwave-define-abbrev "ee" "endelse"      'idlwave-show-begin)
1677(idlwave-define-abbrev "ef" "endfor"       'idlwave-show-begin)
1678(idlwave-define-abbrev "ei" "endif else if" 'idlwave-show-begin)
1679(idlwave-define-abbrev "el" "endif else"   'idlwave-show-begin)
1680(idlwave-define-abbrev "en" "endif"        'idlwave-show-begin)
1681(idlwave-define-abbrev "er" "endrep"       'idlwave-show-begin)
1682(idlwave-define-abbrev "ew" "endwhile"     'idlwave-show-begin)
1683(idlwave-define-abbrev "g"  "goto,"        (idlwave-keyword-abbrev 0 t))
1684(idlwave-define-abbrev "h"  "help,"        (idlwave-keyword-abbrev 0))
1685(idlwave-define-abbrev "k"  "keyword_set()" (idlwave-keyword-abbrev 1))
1686(idlwave-define-abbrev "n"  "n_elements()" (idlwave-keyword-abbrev 1))
1687(idlwave-define-abbrev "on" "on_error,"    (idlwave-keyword-abbrev 0))
1688(idlwave-define-abbrev "oi" "on_ioerror,"  (idlwave-keyword-abbrev 0 1))
1689(idlwave-define-abbrev "ow" "openw,"       (idlwave-keyword-abbrev 0))
1690(idlwave-define-abbrev "or" "openr,"       (idlwave-keyword-abbrev 0))
1691(idlwave-define-abbrev "ou" "openu,"       (idlwave-keyword-abbrev 0))
1692(idlwave-define-abbrev "p"  "print,"       (idlwave-keyword-abbrev 0))
1693(idlwave-define-abbrev "pt" "plot,"        (idlwave-keyword-abbrev 0))
1694(idlwave-define-abbrev "re" "read,"        (idlwave-keyword-abbrev 0))
1695(idlwave-define-abbrev "rf" "readf,"       (idlwave-keyword-abbrev 0))
1696(idlwave-define-abbrev "ru" "readu,"       (idlwave-keyword-abbrev 0))
1697(idlwave-define-abbrev "rt" "return"       (idlwave-keyword-abbrev 0))
1698(idlwave-define-abbrev "sc" "strcompress()" (idlwave-keyword-abbrev 1))
1699(idlwave-define-abbrev "sn" "strlen()"     (idlwave-keyword-abbrev 1))
1700(idlwave-define-abbrev "sl" "strlowcase()" (idlwave-keyword-abbrev 1))
1701(idlwave-define-abbrev "su" "strupcase()"  (idlwave-keyword-abbrev 1))
1702(idlwave-define-abbrev "sm" "strmid()"     (idlwave-keyword-abbrev 1))
1703(idlwave-define-abbrev "sp" "strpos()"     (idlwave-keyword-abbrev 1))
1704(idlwave-define-abbrev "st" "strput()"     (idlwave-keyword-abbrev 1))
1705(idlwave-define-abbrev "sr" "strtrim()"    (idlwave-keyword-abbrev 1))
1706(idlwave-define-abbrev "t"  "then"         (idlwave-keyword-abbrev 0 t))
1707(idlwave-define-abbrev "u"  "until"        (idlwave-keyword-abbrev 0 t))
1708(idlwave-define-abbrev "wu" "writeu,"      (idlwave-keyword-abbrev 0))
1709(idlwave-define-abbrev "iap" "if arg_present() then"     (idlwave-keyword-abbrev 6))
1710(idlwave-define-abbrev "ik" "if keyword_set() then" (idlwave-keyword-abbrev 6))
1711(idlwave-define-abbrev "ine" "if n_elements() eq 0 then" (idlwave-keyword-abbrev 11))
1712(idlwave-define-abbrev "inn" "if n_elements() ne 0 then" (idlwave-keyword-abbrev 11))
1713(idlwave-define-abbrev "np" "n_params()"   (idlwave-keyword-abbrev 0))
1714(idlwave-define-abbrev "s"  "size()"       (idlwave-keyword-abbrev 1))
1715(idlwave-define-abbrev "wi" "widget_info()" (idlwave-keyword-abbrev 1))
1716(idlwave-define-abbrev "wc" "widget_control," (idlwave-keyword-abbrev 0))
1717(idlwave-define-abbrev "pv" "ptr_valid()" (idlwave-keyword-abbrev 1))
1718(idlwave-define-abbrev "ipv" "if ptr_valid() then" (idlwave-keyword-abbrev 6))
1719
1720;; This section is reserved words only. (From IDL user manual)
1721;;
1722(idlwave-define-abbrev "and"        "and"       (idlwave-keyword-abbrev 0 t) t)
1723(idlwave-define-abbrev "begin"      "begin"     (idlwave-keyword-abbrev 0 t) t)
1724(idlwave-define-abbrev "break"      "break"     (idlwave-keyword-abbrev 0 t) t)
1725(idlwave-define-abbrev "case"       "case"      (idlwave-keyword-abbrev 0 t) t)
1726(idlwave-define-abbrev "common"     "common"    (idlwave-keyword-abbrev 0 t) t)
1727(idlwave-define-abbrev "continue"   "continue"  (idlwave-keyword-abbrev 0 t) t)
1728(idlwave-define-abbrev "do"         "do"        (idlwave-keyword-abbrev 0 t) t)
1729(idlwave-define-abbrev "else"       "else"      (idlwave-keyword-abbrev 0 t) t)
1730(idlwave-define-abbrev "end"        "end"       'idlwave-show-begin-check t)
1731(idlwave-define-abbrev "endcase"    "endcase"   'idlwave-show-begin-check t)
1732(idlwave-define-abbrev "endelse"    "endelse"   'idlwave-show-begin-check t)
1733(idlwave-define-abbrev "endfor"     "endfor"    'idlwave-show-begin-check t)
1734(idlwave-define-abbrev "endif"      "endif"     'idlwave-show-begin-check t)
1735(idlwave-define-abbrev "endrep"     "endrep"    'idlwave-show-begin-check t)
1736(idlwave-define-abbrev "endswitch"  "endswitch" 'idlwave-show-begin-check t)
1737(idlwave-define-abbrev "endwhi"     "endwhi"    'idlwave-show-begin-check t)
1738(idlwave-define-abbrev "endwhile"   "endwhile"  'idlwave-show-begin-check t)
1739(idlwave-define-abbrev "eq"         "eq"        (idlwave-keyword-abbrev 0 t) t)
1740(idlwave-define-abbrev "for"        "for"       (idlwave-keyword-abbrev 0 t) t)
1741(idlwave-define-abbrev "function"   "function"  (idlwave-keyword-abbrev 0 t) t)
1742(idlwave-define-abbrev "ge"         "ge"        (idlwave-keyword-abbrev 0 t) t)
1743(idlwave-define-abbrev "goto"       "goto"      (idlwave-keyword-abbrev 0 t) t)
1744(idlwave-define-abbrev "gt"         "gt"        (idlwave-keyword-abbrev 0 t) t)
1745(idlwave-define-abbrev "if"         "if"        (idlwave-keyword-abbrev 0 t) t)
1746(idlwave-define-abbrev "le"         "le"        (idlwave-keyword-abbrev 0 t) t)
1747(idlwave-define-abbrev "lt"         "lt"        (idlwave-keyword-abbrev 0 t) t)
1748(idlwave-define-abbrev "mod"        "mod"       (idlwave-keyword-abbrev 0 t) t)
1749(idlwave-define-abbrev "ne"         "ne"        (idlwave-keyword-abbrev 0 t) t)
1750(idlwave-define-abbrev "not"        "not"       (idlwave-keyword-abbrev 0 t) t)
1751(idlwave-define-abbrev "of"         "of"        (idlwave-keyword-abbrev 0 t) t)
1752(idlwave-define-abbrev "on_ioerror" "on_ioerror" (idlwave-keyword-abbrev 0 t) t)
1753(idlwave-define-abbrev "or"         "or"        (idlwave-keyword-abbrev 0 t) t)
1754(idlwave-define-abbrev "pro"        "pro"       (idlwave-keyword-abbrev 0 t) t)
1755(idlwave-define-abbrev "repeat"     "repeat"    (idlwave-keyword-abbrev 0 t) t)
1756(idlwave-define-abbrev "switch"     "switch"    (idlwave-keyword-abbrev 0 t) t)
1757(idlwave-define-abbrev "then"       "then"      (idlwave-keyword-abbrev 0 t) t)
1758(idlwave-define-abbrev "until"      "until"     (idlwave-keyword-abbrev 0 t) t)
1759(idlwave-define-abbrev "while"      "while"     (idlwave-keyword-abbrev 0 t) t)
1760(idlwave-define-abbrev "xor"        "xor"       (idlwave-keyword-abbrev 0 t) t)
1761
1762(defvar imenu-create-index-function)
1763(defvar extract-index-name-function)
1764(defvar prev-index-position-function)
1765(defvar imenu-extract-index-name-function)
1766(defvar imenu-prev-index-position-function)
1767;; defined later - so just make the compiler hush
1768(defvar idlwave-mode-menu)
1769(defvar idlwave-mode-debug-menu)
1770
1771;;;###autoload
1772(define-derived-mode idlwave-mode prog-mode "IDLWAVE"
1773  "Major mode for editing IDL source files (version 6.1_em22).
1774
1775The main features of this mode are
1776
17771. Indentation and Formatting
1778   --------------------------
1779   Like other Emacs programming modes, C-j inserts a newline and indents.
1780   TAB is used for explicit indentation of the current line.
1781
1782   To start a continuation line, use \\[idlwave-split-line].  This
1783   function can also be used in the middle of a line to split the line
1784   at that point.  When used inside a long constant string, the string
1785   is split at that point with the `+' concatenation operator.
1786
1787   Comments are indented as follows:
1788
1789   `;;;' Indentation remains unchanged.
1790   `;;'  Indent like the surrounding code
1791   `;'   Indent to a minimum column.
1792
1793   The indentation of comments starting in column 0 is never changed.
1794
1795   Use \\[idlwave-fill-paragraph] to refill a paragraph inside a
1796   comment.  The indentation of the second line of the paragraph
1797   relative to the first will be retained.  Use
1798   \\[idlwave-auto-fill-mode] to toggle auto-fill mode for these
1799   comments.  When the variable `idlwave-fill-comment-line-only' is
1800   nil, code can also be auto-filled and auto-indented.
1801
1802   To convert pre-existing IDL code to your formatting style, mark the
1803   entire buffer with \\[mark-whole-buffer] and execute
1804   \\[idlwave-expand-region-abbrevs].  Then mark the entire buffer
1805   again followed by \\[indent-region] (`indent-region').
1806
18072. Routine Info
1808   ------------
1809   IDLWAVE displays information about the calling sequence and the
1810   accepted keyword parameters of a procedure or function with
1811   \\[idlwave-routine-info].  \\[idlwave-find-module] jumps to the
1812   source file of a module.  These commands know about system
1813   routines, all routines in idlwave-mode buffers and (when the
1814   idlwave-shell is active) about all modules currently compiled under
1815   this shell.  It also makes use of pre-compiled or custom-scanned
1816   user and library catalogs many popular libraries ship with by
1817   default.  Use \\[idlwave-update-routine-info] to update this
1818   information, which is also used for completion (see item 4).
1819
18203. Online IDL Help
1821   ---------------
1822
1823   \\[idlwave-context-help] displays the IDL documentation relevant
1824   for the system variable, keyword, or routines at point.  A single
1825   key stroke gets you directly to the right place in the docs.  See
1826   the manual to configure where and how the HTML help is displayed.
1827
18284. Completion
1829   ----------
1830   \\[idlwave-complete] completes the names of procedures, functions
1831   class names, keyword parameters, system variables and tags, class
1832   tags, structure tags, filenames and much more.  It is context
1833   sensitive and figures out what is expected at point.  Lower case
1834   strings are completed in lower case, other strings in mixed or
1835   upper case.
1836
18375. Code Templates and Abbreviations
1838   --------------------------------
1839   Many Abbreviations are predefined to expand to code fragments and templates.
1840   The abbreviations start generally with a `\\'.  Some examples:
1841
1842   \\pr        PROCEDURE template
1843   \\fu        FUNCTION template
1844   \\c         CASE statement template
1845   \\sw        SWITCH statement template
1846   \\f         FOR loop template
1847   \\r         REPEAT Loop template
1848   \\w         WHILE loop template
1849   \\i         IF statement template
1850   \\elif      IF-ELSE statement template
1851   \\b         BEGIN
1852
1853   For a full list, use \\[idlwave-list-abbrevs].  Some templates also
1854   have direct keybindings - see the list of keybindings below.
1855
1856   \\[idlwave-doc-header] inserts a documentation header at the
1857   beginning of the current program unit (pro, function or main).
1858   Change log entries can be added to the current program unit with
1859   \\[idlwave-doc-modification].
1860
18616. Automatic Case Conversion
1862   -------------------------
1863   The case of reserved words and some abbrevs is controlled by
1864   `idlwave-reserved-word-upcase' and `idlwave-abbrev-change-case'.
1865
18667. Automatic END completion
1867   ------------------------
1868   If the variable `idlwave-expand-generic-end' is non-nil, each END typed
1869   will be converted to the specific version, like ENDIF, ENDFOR, etc.
1870
18718. Hooks
1872   -----
1873   Loading idlwave.el runs `idlwave-load-hook'.
1874   Turning on `idlwave-mode' runs `idlwave-mode-hook'.
1875
18769. Documentation and Customization
1877   -------------------------------
1878   Info documentation for this package is available.  Use
1879   \\[idlwave-info] to display (complain to your sysadmin if that does
1880   not work).  For Postscript, PDF, and HTML versions of the
1881   documentation, check IDLWAVE's homepage at URL
1882   `http://github.com/jdtsmith/idlwave'.
1883   IDLWAVE has customize support - see the group `idlwave'.
1884
188510.Keybindings
1886   -----------
1887   Here is a list of all keybindings of this mode.
1888   If some of the key bindings below show with ??, use \\[describe-key]
1889   followed by the key sequence to see what the key sequence does.
1890
1891\\{idlwave-mode-map}"
1892  :abbrev-table idlwave-mode-abbrev-table
1893  (if idlwave-startup-message
1894      (message "Emacs IDLWAVE mode version %s." idlwave-mode-version))
1895  (setq idlwave-startup-message nil)
1896
1897  (set (make-local-variable 'indent-line-function) 'idlwave-indent-and-action)
1898
1899  (set (make-local-variable idlwave-comment-indent-function)
1900       #'idlwave-comment-hook)
1901
1902  (set (make-local-variable 'comment-start-skip) ";+[ \t]*")
1903  (set (make-local-variable 'comment-start) ";")
1904  (set (make-local-variable 'comment-add) 1) ; ";;" for new and regions
1905  (set (make-local-variable 'abbrev-all-caps) t)
1906  (set (make-local-variable 'indent-tabs-mode) nil)
1907  (set (make-local-variable 'completion-ignore-case) t)
1908
1909  (when (featurep 'easymenu)
1910    (easy-menu-add idlwave-mode-menu idlwave-mode-map)
1911    (easy-menu-add idlwave-mode-debug-menu idlwave-mode-map))
1912
1913  (setq abbrev-mode t)
1914
1915  (set (make-local-variable idlwave-fill-function) 'idlwave-auto-fill)
1916  (setq comment-end "")
1917  (set (make-local-variable 'comment-multi-line) nil)
1918  (set (make-local-variable 'paragraph-separate)
1919       "[ \t\f]*$\\|[ \t]*;+[ \t]*$\\|;+[+=-_*]+$")
1920  (set (make-local-variable 'paragraph-start) "[ \t\f]\\|[ \t]*;+[ \t]")
1921  (set (make-local-variable 'paragraph-ignore-fill-prefix) nil)
1922  (set (make-local-variable 'parse-sexp-ignore-comments) t)
1923
1924  ;; ChangeLog
1925  (set (make-local-variable 'add-log-current-defun-function)
1926       'idlwave-current-routine-fullname)
1927
1928  ;; Set tag table list to use IDLTAGS as file name.
1929  (if (boundp 'tag-table-alist)
1930      (add-to-list 'tag-table-alist '("\\.pro$" . "IDLTAGS")))
1931
1932  ;; Font-lock additions
1933  ;; Following line is for Emacs - XEmacs uses the corresponding property
1934  ;; on the `idlwave-mode' symbol.
1935  (set (make-local-variable 'font-lock-defaults) idlwave-font-lock-defaults)
1936  (set (make-local-variable 'font-lock-mark-block-function)
1937       'idlwave-mark-subprogram)
1938  (set (make-local-variable 'font-lock-fontify-region-function)
1939       'idlwave-font-lock-fontify-region)
1940
1941  ;; Imenu setup
1942  (set (make-local-variable 'imenu-create-index-function)
1943       'imenu-default-create-index-function)
1944  (set (make-local-variable 'imenu-extract-index-name-function)
1945       'idlwave-unit-name)
1946  (set (make-local-variable 'imenu-prev-index-position-function)
1947       'idlwave-prev-index-position)
1948
1949  ;; HideShow setup
1950  (add-to-list 'hs-special-modes-alist
1951	       (list 'idlwave-mode
1952		     idlwave-begin-block-reg
1953		     idlwave-end-block-reg
1954		     ";"
1955		     'idlwave-forward-block nil))
1956
1957  ;; Make a local post-command-hook and add our hook to it
1958  ;; NB: `make-local-hook' needed for older/alternative Emacs compatibility
1959  ;; (make-local-hook 'post-command-hook)
1960  (add-hook 'post-command-hook 'idlwave-command-hook nil 'local)
1961
1962  ;; Make local hooks for buffer updates
1963  ;; NB: `make-local-hook' needed for older/alternative Emacs compatibility
1964  ;; (make-local-hook 'kill-buffer-hook)
1965  (add-hook 'kill-buffer-hook 'idlwave-kill-buffer-update nil 'local)
1966  ;; (make-local-hook 'after-save-hook)
1967  (add-hook 'after-save-hook 'idlwave-save-buffer-update nil 'local)
1968  (add-hook 'after-save-hook 'idlwave-revoke-license-to-kill nil 'local)
1969
1970  ;; Setup directories and file, if necessary
1971  (idlwave-setup)
1972
1973  ;; Update the routine info with info about current buffer?
1974  (idlwave-new-buffer-update)
1975
1976  ;; Check help location
1977  (idlwave-help-check-locations))
1978
1979(defvar idlwave-setup-done nil)
1980(defun idlwave-setup ()
1981  (unless idlwave-setup-done
1982    (if (not (file-directory-p idlwave-config-directory))
1983	(make-directory idlwave-config-directory))
1984    (setq
1985     idlwave-user-catalog-file (expand-file-name
1986				idlwave-user-catalog-file
1987				idlwave-config-directory)
1988     idlwave-xml-system-rinfo-converted-file
1989     (expand-file-name
1990      idlwave-xml-system-rinfo-converted-file
1991      idlwave-config-directory)
1992     idlwave-path-file (expand-file-name
1993			idlwave-path-file
1994			idlwave-config-directory))
1995    (idlwave-read-paths)  ; we may need these early
1996    (setq idlwave-setup-done t)))
1997
1998(defun idlwave-font-lock-fontify-region (beg end &optional verbose)
1999  "Fontify continuation lines correctly."
2000  (let (pos)
2001    (save-excursion
2002      (goto-char beg)
2003      (forward-line -1)
2004      (when (setq pos (idlwave-is-continuation-line))
2005	(goto-char pos)
2006	(idlwave-beginning-of-statement)
2007	(setq beg (point)))))
2008  (font-lock-default-fontify-region beg end verbose))
2009
2010;;
2011;; Code Formatting ----------------------------------------------------
2012;;
2013
2014(defun idlwave-hard-tab ()
2015  "Insert TAB in buffer in current position."
2016  (interactive)
2017  (insert "\t"))
2018
2019;;; This stuff is experimental
2020
2021(defvar idlwave-command-hook nil
2022  "If non-nil, a list that can be evaluated using `eval'.
2023It is evaluated in the lisp function `idlwave-command-hook' which is
2024placed in `post-command-hook'.")
2025
2026(defun idlwave-command-hook ()
2027  "Command run after every command.
2028Evaluates a non-nil value of the *variable* `idlwave-command-hook' and
2029sets the variable to zero afterwards."
2030  (and idlwave-command-hook
2031       (listp idlwave-command-hook)
2032       (condition-case nil
2033	   (eval idlwave-command-hook)
2034	 (error nil)))
2035  (setq idlwave-command-hook nil))
2036
2037;;; End experiment
2038
2039;; It would be better to use expand.el for better abbrev handling and
2040;; versatility.
2041
2042(defun idlwave-check-abbrev (arg &optional reserved)
2043  "Reverse abbrev expansion if in comment or string.
2044Argument ARG is the number of characters to move point
2045backward if `idlwave-abbrev-move' is non-nil.
2046If optional argument RESERVED is non-nil then the expansion
2047consists of reserved words, which will be capitalized if
2048`idlwave-reserved-word-upcase' is non-nil.
2049Otherwise, the abbrev will be capitalized if `idlwave-abbrev-change-case'
2050is non-nil, unless its value is `down' in which case the abbrev will be
2051made into all lowercase.
2052Returns non-nil if abbrev is left expanded."
2053  (if (idlwave-quoted)
2054      (progn (unexpand-abbrev)
2055             nil)
2056    (if (and reserved idlwave-reserved-word-upcase)
2057        (upcase-region last-abbrev-location (point))
2058      (cond
2059       ((equal idlwave-abbrev-change-case 'down)
2060        (downcase-region last-abbrev-location (point)))
2061       (idlwave-abbrev-change-case
2062        (upcase-region last-abbrev-location (point)))))
2063    (if (and idlwave-abbrev-move (> arg 0))
2064        (if (boundp 'post-command-hook)
2065            (setq idlwave-command-hook (list 'backward-char (1+ arg)))
2066          (backward-char arg)))
2067    t))
2068
2069(defun idlwave-in-comment ()
2070  "Return t if point is inside a comment, nil otherwise."
2071  (save-excursion
2072    (let ((here (point)))
2073      (and (idlwave-goto-comment) (> here (point))))))
2074
2075(defun idlwave-goto-comment ()
2076  "Move to start of comment delimiter on current line.
2077Moves to end of line if there is no comment delimiter.
2078Ignores comment delimiters in strings.
2079Returns point if comment found and nil otherwise."
2080  (let ((eos (point-at-eol))
2081        (data (match-data))
2082        found)
2083    ;; Look for first comment delimiter not in a string
2084    (beginning-of-line)
2085    (setq found (search-forward comment-start eos 'lim))
2086    (while (and found (idlwave-in-quote))
2087      (setq found (search-forward comment-start eos 'lim)))
2088    (store-match-data data)
2089    (and found (not (idlwave-in-quote))
2090         (progn
2091           (backward-char 1)
2092           (point)))))
2093
2094(defun idlwave-region-active-p ()
2095  "Should we operate on an active region?"
2096  (if (fboundp 'use-region-p)
2097      (use-region-p)
2098    (region-active-p)))
2099
2100(defun idlwave-show-matching-quote ()
2101  "Insert quote and show matching quote if this is end of a string."
2102  (interactive)
2103  (let ((bq (idlwave-in-quote))
2104        (inq last-command-event))
2105    (if (and bq (not (idlwave-in-comment)))
2106        (let ((delim (char-after bq)))
2107          (insert inq)
2108          (if (eq inq delim)
2109              (save-excursion
2110                (goto-char bq)
2111                (sit-for 1))))
2112      ;; Not the end of a string
2113      (insert inq))))
2114
2115(defun idlwave-show-begin-check ()
2116  "Ensure that the previous word was a token before `idlwave-show-begin'.
2117An END token must be preceded by whitespace."
2118  (if (not (idlwave-quoted))
2119      (if
2120	  (save-excursion
2121	    (backward-word-strictly 1)
2122	    (backward-char 1)
2123	    (looking-at "[ \t\n\f]"))
2124	  (idlwave-show-begin))))
2125
2126(defun idlwave-show-begin ()
2127  "Find the start of current block and blinks to it for a second.
2128Also checks if the correct END statement has been used."
2129  ;; All end statements are reserved words
2130  ;; Re-indent end line
2131  ;;(insert-char ?\  1) ;; So indent, etc. work well
2132  ;;(backward-char 1)
2133  (let* ((pos (point-marker))
2134	 (last-abbrev-marker (copy-marker last-abbrev-location))
2135	 (eol-pos (point-at-eol))
2136	 begin-pos end-pos end end1 )
2137    (if idlwave-reindent-end  (idlwave-indent-line))
2138    (setq last-abbrev-location (marker-position last-abbrev-marker))
2139    (when (and (idlwave-check-abbrev 0 t)
2140	       idlwave-show-block)
2141      (save-excursion
2142	;; Move inside current block
2143	(goto-char last-abbrev-marker)
2144	(idlwave-block-jump-out -1 'nomark)
2145	(setq begin-pos (point))
2146	(idlwave-block-jump-out 1 'nomark)
2147	(setq end-pos (point))
2148	(if (> end-pos eol-pos)
2149	    (setq end-pos pos))
2150	(goto-char end-pos)
2151	(setq end (buffer-substring
2152		   (progn
2153		     (skip-chars-backward "a-zA-Z")
2154		     (point))
2155		   end-pos))
2156	(goto-char begin-pos)
2157	(when (setq end1 (cdr (idlwave-block-master)))
2158	  (cond
2159	   ((null end1)) ; no-operation
2160	   ((string= (downcase end) (downcase end1))
2161	    (sit-for 1))
2162	   ((string= (downcase end) "end")
2163	    ;; A generic end
2164	    (if idlwave-expand-generic-end
2165		(save-excursion
2166		  (goto-char pos)
2167		  (backward-char 3)
2168		  (insert (if (string= end "END") (upcase end1) end1))
2169		  (delete-char 3)))
2170	    (sit-for 1))
2171	   (t
2172	    (beep)
2173	    (message "Warning: Shouldn't this be \"%s\" instead of \"%s\"?"
2174		     end1 end)
2175	    (sit-for 1))))))))
2176  ;;(delete-char 1))
2177
2178(defun idlwave-block-master ()
2179  (let ((case-fold-search t))
2180    (save-excursion
2181      (cond
2182       ((looking-at "pro\\|case\\|switch\\|function\\>")
2183	(assoc (downcase (match-string 0)) idlwave-block-matches))
2184       ((looking-at "begin\\>")
2185	(let ((limit (save-excursion
2186		       (idlwave-beginning-of-statement)
2187		       (point))))
2188	  (cond
2189	   ((re-search-backward ":[ \t]*\\=" limit t)
2190	    ;; seems to be a case thing
2191	    '("begin" . "end"))
2192	   ((re-search-backward idlwave-block-match-regexp limit t)
2193	    (assoc (downcase (match-string 1))
2194		   idlwave-block-matches))
2195	   (t
2196	    ;; Just a normal block
2197	    '("begin" . "end")))))
2198       (t nil)))))
2199
2200(defun idlwave-close-block ()
2201  "Terminate the current block with the correct END statement."
2202  (interactive)
2203  ;; Start new line if we are not in a new line
2204  (unless (save-excursion
2205	    (skip-chars-backward " \t")
2206	    (bolp))
2207    (let ((idlwave-show-block nil))
2208      (newline-and-indent)))
2209  (let ((last-abbrev-location (point)))  ; for upcasing
2210    (insert "end")
2211    (idlwave-show-begin)))
2212
2213(defun idlwave-custom-ampersand-surround (&optional is-action)
2214  "Surround &, leaving room for && (which surround as well)."
2215  (let* ((prev-char (char-after (- (point) 2)))
2216	 (next-char (char-after (point)))
2217	 (amp-left (eq prev-char ?&))
2218	 (amp-right (eq next-char ?&))
2219	 (len (if amp-left 2 1)))
2220    (unless amp-right ;no need to do it twice, amp-left will catch it.
2221      (idlwave-surround -1 (if (or is-action amp-left) -1) len))))
2222
2223(defun idlwave-custom-ltgtr-surround (gtr &optional is-action)
2224  "Surround > and < by blanks, leaving room for >= and <=, and considering ->."
2225  (let* ((prev-char (char-after (- (point) 2)))
2226	(next-char (char-after (point)))
2227	(method-invoke (and gtr (eq prev-char ?-)))
2228	(len (if method-invoke 2 1)))
2229    (unless  (eq next-char ?=)
2230      ;; Key binding: pad only on left, to save for possible >=/<=
2231      (idlwave-surround -1 (if (or is-action method-invoke) -1) len))))
2232
2233(defun idlwave-surround (&optional before after length is-action)
2234  "Surround the LENGTH characters before point with blanks.
2235LENGTH defaults to 1.
2236Optional arguments BEFORE and AFTER affect the behavior before and
2237after the characters (see also description of `idlwave-make-space'):
2238
2239nil            do nothing
22400              force no spaces
2241integer > 0    force exactly n spaces
2242integer < 0    at least |n| spaces
2243
2244The function does nothing if any of the following conditions is true:
2245- `idlwave-surround-by-blank' is nil
2246- the character before point is inside a string or comment"
2247  (when (and idlwave-surround-by-blank (not (idlwave-quoted)))
2248    (let ((length (or length 1))) ; establish a default for LENGTH
2249      (backward-char length)
2250      (save-restriction
2251	(let ((here (point)))
2252	  (skip-chars-backward " \t")
2253	  (if (bolp)
2254	      ;; avoid clobbering indent
2255	      (progn
2256		(move-to-column (idlwave-calculate-indent))
2257		(if (<= (point) here)
2258		    (narrow-to-region (point) here))
2259		(goto-char here)))
2260	  (idlwave-make-space before))
2261	(skip-chars-forward " \t"))
2262      (forward-char length)
2263      (idlwave-make-space after)
2264      ;; Check to see if the line should auto wrap
2265      (if (and (equal (char-after (1- (point))) ?\ )
2266	       (> (current-column) fill-column))
2267	  (funcall auto-fill-function)))))
2268
2269(defun idlwave-make-space (n)
2270  "Make space at point.
2271The space affected is all the spaces and tabs around point.
2272If n is non-nil then point is left abs(n) spaces from the beginning of
2273the contiguous space.
2274The amount of space at point is determined by N.
2275If the value of N is:
2276nil   - do nothing.
2277> 0   - exactly N spaces.
2278< 0   - a minimum of -N spaces, i.e., do not change if there are
2279        already -N spaces.
22800     - no spaces (i.e. remove any existing space)."
2281  (if (integerp n)
2282      (let
2283          ((start-col (progn (skip-chars-backward " \t") (current-column)))
2284           (left (point))
2285           (end-col (progn (skip-chars-forward " \t") (current-column))))
2286        (delete-horizontal-space)
2287        (cond
2288         ((> n 0)
2289          (idlwave-indent-to (+ start-col n))
2290          (goto-char (+ left n)))
2291         ((< n 0)
2292          (idlwave-indent-to end-col (- n))
2293          (goto-char (- left n)))
2294         ;; n = 0, done
2295         ))))
2296
2297(defun idlwave-newline ()
2298  "Insert a newline and indent the current and previous line."
2299  (interactive)
2300  ;;
2301  ;; Handle unterminated single and double quotes
2302  ;; If not in a comment and in a string then insertion of a newline
2303  ;; will mean unbalanced quotes.
2304  ;;
2305  (if (and (not (idlwave-in-comment)) (idlwave-in-quote))
2306      (progn (beep)
2307             (message "Warning: unbalanced quotes?")))
2308  (newline)
2309  ;;
2310  ;; The current line is being split, the cursor should be at the
2311  ;; beginning of the new line skipping the leading indentation.
2312  ;;
2313  ;; The reason we insert the new line before indenting is that the
2314  ;; indenting could be confused by keywords (e.g. END) on the line
2315  ;; after the split point.  This prevents us from just using
2316  ;; `indent-for-tab-command' followed by `newline-and-indent'.
2317  ;;
2318  (beginning-of-line 0)
2319  (idlwave-indent-line)
2320  (forward-line)
2321  (idlwave-indent-line))
2322
2323;;
2324;;  Use global variable 'comment-column' to set parallel comment
2325;;
2326;; Modeled on lisp.el
2327;; Emacs Lisp and IDL (Wave CL) have identical comment syntax
2328(defun idlwave-comment-hook ()
2329  "Compute indent for the beginning of the IDL comment delimiter."
2330  (if (or (looking-at idlwave-no-change-comment)
2331          (looking-at (or idlwave-begin-line-comment "^;")))
2332      (current-column)
2333    (if (looking-at idlwave-code-comment)
2334        (if (save-excursion (skip-chars-backward " \t") (bolp))
2335            ;; On line by itself, indent as code
2336            (let ((tem (idlwave-calculate-indent)))
2337              (if (listp tem) (car tem) tem))
2338          ;; after code - do not change
2339          (current-column))
2340      (skip-chars-backward " \t")
2341      (max (if (bolp) 0 (1+ (current-column)))
2342           comment-column))))
2343
2344(defun idlwave-split-line ()
2345  "Continue line by breaking line at point and indent the lines.
2346For a code line insert continuation marker.  If the line is a line comment
2347then the new line will contain a comment with the same indentation.
2348Splits strings with the IDL operator `+' if `idlwave-split-line-string' is
2349non-nil."
2350  (interactive)
2351  ;; Expand abbreviation, just like normal RET would.
2352  (and abbrev-mode (expand-abbrev))
2353  (let (beg)
2354    (if (not (idlwave-in-comment))
2355        ;; For code line add continuation.
2356        ;; Check if splitting a string.
2357        (progn
2358          (if (setq beg (idlwave-in-quote))
2359              (if idlwave-split-line-string
2360                  ;; Split the string.
2361                  (progn (insert (setq beg (char-after beg)) " + "
2362                                 idlwave-continuation-char beg)
2363                         (backward-char 1)
2364			 (newline-and-indent)
2365			 (forward-char 1))
2366                ;; Do not split the string.
2367                (beep)
2368                (message "Warning: continuation inside string!!")
2369                (insert " " idlwave-continuation-char))
2370            ;; Not splitting a string.
2371	    (if (not (member (char-before) '(?\  ?\t)))
2372		(insert " "))
2373            (insert idlwave-continuation-char)
2374	    (newline-and-indent)))
2375      (indent-new-comment-line))
2376    ;; Indent previous line
2377    (setq beg (- (point-max) (point)))
2378    (forward-line -1)
2379    (idlwave-indent-line)
2380    (goto-char (- (point-max) beg))
2381    ;; Reindent new line
2382    (idlwave-indent-line)))
2383
2384(defun idlwave-beginning-of-subprogram (&optional nomark)
2385  "Move point to the beginning of the current program unit.
2386If NOMARK is non-nil, do not push mark."
2387  (interactive)
2388  (idlwave-find-key idlwave-begin-unit-reg -1 nomark))
2389
2390(defun idlwave-end-of-subprogram (&optional nomark)
2391  "Move point to the start of the next program unit.
2392If NOMARK is non-nil, do not push mark."
2393  (interactive)
2394  (idlwave-end-of-statement)
2395  (idlwave-find-key idlwave-end-unit-reg 1 nomark))
2396
2397(defun idlwave-mark-statement ()
2398  "Mark current IDL statement."
2399  (interactive)
2400  (idlwave-end-of-statement)
2401  (let ((end (point)))
2402    (idlwave-beginning-of-statement)
2403    (push-mark end nil t)))
2404
2405(defun idlwave-mark-block ()
2406  "Mark containing block."
2407  (interactive)
2408  (idlwave-end-of-statement)
2409  (idlwave-backward-up-block -1)
2410  (idlwave-end-of-statement)
2411  (let ((end (point)))
2412    (idlwave-backward-block)
2413    (idlwave-beginning-of-statement)
2414    (push-mark end nil t)))
2415
2416
2417(defun idlwave-mark-subprogram ()
2418  "Put mark at beginning of program, point at end.
2419The marks are pushed."
2420  (interactive)
2421  (idlwave-end-of-statement)
2422  (idlwave-beginning-of-subprogram)
2423  (let ((beg (point)))
2424    (idlwave-forward-block)
2425    (push-mark beg nil t))
2426  (exchange-point-and-mark))
2427
2428(defun idlwave-backward-up-block (&optional arg)
2429  "Move to beginning of enclosing block if prefix ARG >= 0.
2430If prefix ARG < 0 then move forward to enclosing block end."
2431  (interactive "p")
2432  (idlwave-block-jump-out (- arg) 'nomark))
2433
2434(defun idlwave-beginning-of-block ()
2435  "Go to the beginning of the current block."
2436  (interactive)
2437  (idlwave-block-jump-out -1 'nomark)
2438  (forward-word-strictly 1))
2439
2440(defun idlwave-end-of-block ()
2441  "Go to the beginning of the current block."
2442  (interactive)
2443  (idlwave-block-jump-out 1 'nomark)
2444  (backward-word-strictly 1))
2445
2446(defun idlwave-forward-block (&optional arg)
2447  "Move across next nested block."
2448  (interactive)
2449  (let ((arg (or arg 1)))
2450    (if (idlwave-down-block arg)
2451	(idlwave-block-jump-out arg 'nomark))))
2452
2453(defun idlwave-backward-block ()
2454  "Move backward across previous nested block."
2455  (interactive)
2456  (if (idlwave-down-block -1)
2457      (idlwave-block-jump-out -1 'nomark)))
2458
2459(defun idlwave-down-block (&optional arg)
2460  "Go down a block.
2461With ARG: ARG >= 0 go forwards, ARG < 0 go backwards.
2462Returns non-nil if successful."
2463  (interactive "p")
2464  (let (status)
2465    (if (< arg 0)
2466        ;; Backward
2467        (let ((eos (save-excursion
2468                     (idlwave-block-jump-out -1 'nomark)
2469                     (point))))
2470          (if (setq status (idlwave-find-key
2471			    idlwave-end-block-reg -1 'nomark eos))
2472              (idlwave-beginning-of-statement)
2473            (message "No nested block before beginning of containing block.")))
2474      ;; Forward
2475      (let ((eos (save-excursion
2476                   (idlwave-block-jump-out 1 'nomark)
2477                   (point))))
2478        (if (setq status (idlwave-find-key
2479			  idlwave-begin-block-reg 1 'nomark eos))
2480            (idlwave-end-of-statement)
2481          (message "No nested block before end of containing block."))))
2482    status))
2483
2484(defun idlwave-mark-doclib ()
2485  "Put point at beginning of doc library header, mark at end.
2486The marks are pushed."
2487  (interactive)
2488  (let (beg
2489        (here (point)))
2490    (goto-char (point-max))
2491    (if (re-search-backward idlwave-doclib-start nil t)
2492        (progn
2493	  (setq beg (progn (beginning-of-line) (point)))
2494	  (if (re-search-forward idlwave-doclib-end nil t)
2495	      (progn
2496		(forward-line 1)
2497		(push-mark beg nil t)
2498		(message "Could not find end of doc library header.")))
2499	  (message "Could not find doc library header start.")
2500	  (goto-char here)))))
2501
2502(defun idlwave-current-routine-fullname ()
2503  (let ((name (idlwave-current-routine)))
2504    (idlwave-make-full-name (nth 2 name) (car name))))
2505
2506(defun idlwave-current-routine ()
2507  "Return (NAME TYPE CLASS) of current routine."
2508  (idlwave-routines)
2509  (save-excursion
2510    (idlwave-beginning-of-subprogram 'nomark)
2511    (if (looking-at "[ \t]*\\<\\(pro\\|function\\)\\>\\s-+\\(\\([a-zA-Z0-9$_]+\\)::\\)?\\([a-zA-Z0-9$_]+\\)")
2512	(let* ((type (if (string= (downcase (match-string 1)) "pro")
2513			 'pro 'function))
2514	       (class (idlwave-sintern-class (match-string 3)))
2515	       (name (idlwave-sintern-routine-or-method (match-string 4) class)))
2516	  (list name type class)))))
2517
2518(defvar idlwave-shell-prompt-pattern)
2519(defun idlwave-beginning-of-statement ()
2520  "Move to beginning of the current statement.
2521Skips back past statement continuations.
2522Point is placed at the beginning of the line whether or not this is an
2523actual statement."
2524  (interactive)
2525  (cond
2526   ((derived-mode-p 'idlwave-shell-mode)
2527    (if (re-search-backward idlwave-shell-prompt-pattern nil t)
2528	(goto-char (match-end 0))))
2529   (t
2530    (if (save-excursion (forward-line -1) (idlwave-is-continuation-line))
2531	(idlwave-previous-statement)
2532      (beginning-of-line)))))
2533
2534(defun idlwave-previous-statement ()
2535  "Move point to beginning of the previous statement.
2536Returns t if the current line before moving is the beginning of
2537the first non-comment statement in the file, and nil otherwise."
2538  (interactive)
2539  (let (first-statement)
2540    (if (not (= (forward-line -1) 0))
2541        ;; first line in file
2542        t
2543      ;; skip blank lines, label lines, include lines and line comments
2544      (while (and
2545              ;; The current statement is the first statement until we
2546              ;; reach another statement.
2547              (setq first-statement
2548                    (or
2549                     (looking-at idlwave-comment-line-start-skip)
2550                     (looking-at "[ \t]*$")
2551                     (looking-at (concat "[ \t]*" idlwave-label "[ \t]*$"))
2552                     (looking-at "^@")))
2553              (= (forward-line -1) 0)))
2554      ;; skip continuation lines
2555      (while (and
2556              (save-excursion
2557                (forward-line -1)
2558                (idlwave-is-continuation-line))
2559              (= (forward-line -1) 0)))
2560      first-statement)))
2561
2562(defun idlwave-end-of-statement ()
2563  "Move point to the end of the current IDL statement.
2564If not in a statement just moves to end of line.  Returns position."
2565  (interactive)
2566  (while (and (idlwave-is-continuation-line)
2567              (= (forward-line 1) 0))
2568    (while (and (idlwave-is-comment-or-empty-line)
2569		(= (forward-line 1) 0))))
2570  (end-of-line)
2571  (point))
2572
2573(defun idlwave-end-of-statement0 ()
2574  "Move point to the end of the current IDL statement.
2575If not in a statement just moves to end of line.  Returns position."
2576  (interactive)
2577  (while (and (idlwave-is-continuation-line)
2578              (= (forward-line 1) 0)))
2579  (end-of-line)
2580  (point))
2581
2582(defun idlwave-next-statement ()
2583  "Move point to beginning of the next IDL statement.
2584Returns t if that statement is the last non-comment IDL statement
2585in the file, and nil otherwise."
2586  (interactive)
2587  (let (last-statement)
2588    (idlwave-end-of-statement)
2589    ;; skip blank lines, label lines, include lines and line comments
2590    (while (and (= (forward-line 1) 0)
2591                ;; The current statement is the last statement until
2592                ;; we reach a new statement.
2593                (setq last-statement
2594                      (or
2595                       (looking-at idlwave-comment-line-start-skip)
2596                       (looking-at "[ \t]*$")
2597                       (looking-at (concat "[ \t]*" idlwave-label "[ \t]*$"))
2598                       (looking-at "^@")))))
2599    last-statement))
2600
2601(defun idlwave-skip-multi-commands (&optional lim)
2602  "Skip past multiple commands on a line (with `&')."
2603  (let ((save-point (point)))
2604    (when (re-search-forward ".*&" lim t)
2605      (goto-char (match-end 0))
2606      (if (idlwave-quoted)
2607	  (goto-char save-point)
2608	(if (eq (char-after (- (point) 2)) ?&) (goto-char save-point))))
2609    (point)))
2610
2611(defun idlwave-skip-label-or-case ()
2612  "Skip label or case statement element.
2613Returns position after label.
2614If there is no label point is not moved and nil is returned."
2615  ;; Case expressions and labels are terminated by a colon.
2616  ;; So we find the first colon in the line and make sure
2617  ;; - no `?' is before it (might be a ? b : c)
2618  ;; - it is not in a comment
2619  ;; - not in a string constant
2620  ;; - not in parenthesis (like a[0:3])
2621  ;; - not followed by another ":" in explicit class, ala a->b::c
2622  ;; As many in this mode, this function is heuristic and not an exact
2623  ;; parser.
2624  (let* ((start (point))
2625	 (eos (save-excursion (idlwave-end-of-statement) (point)))
2626	 (end (idlwave-find-key ":" 1 'nomark eos)))
2627    (if (and end
2628             (= (nth 0 (parse-partial-sexp start end)) 0)
2629	     (not (string-match "\\?" (buffer-substring start end)))
2630	     (not (string-match "^::" (buffer-substring end eos))))
2631        (progn
2632          (forward-char)
2633          (point))
2634      (goto-char start)
2635      nil)))
2636
2637(defun idlwave-start-of-substatement (&optional pre)
2638  "Move to start of next IDL substatement after point.
2639Uses the type of the current IDL statement to determine if the next
2640statement is on a new line or is a subpart of the current statement.
2641Returns point at start of substatement modulo whitespace.
2642If optional argument is non-nil move to beginning of current
2643substatement."
2644  (let ((orig (point))
2645        (eos (idlwave-end-of-statement))
2646        (ifnest 0)
2647        st nst last)
2648    (idlwave-beginning-of-statement)
2649    (idlwave-skip-label-or-case)
2650    (if (< (point) orig)
2651	(idlwave-skip-multi-commands orig))
2652    (setq last (point))
2653    ;; Continue looking for substatements until we are past orig
2654    (while (and (<= (point) orig) (not (eobp)))
2655      (setq last (point))
2656      (setq nst (nth 1 (cdr (setq st (car (idlwave-statement-type))))))
2657      (if (equal (car st) 'if) (setq ifnest (1+ ifnest)))
2658      (cond ((and nst
2659                  (idlwave-find-key nst 1 'nomark eos))
2660             (goto-char (match-end 0)))
2661            ((and (> ifnest 0) (idlwave-find-key "\\<else\\>" 1 'nomark eos))
2662             (setq ifnest (1- ifnest))
2663             (goto-char (match-end 0)))
2664            (t (setq ifnest 0)
2665               (idlwave-next-statement))))
2666    (if pre (goto-char last))
2667    ;; If a continuation line starts here, move to next line
2668    (if (looking-at "[ \t]*\\$\\([ \t]*\\(;\\|$\\)\\)")
2669	(beginning-of-line 2))
2670    (point)))
2671
2672(defun idlwave-statement-type ()
2673  "Return the type of the current IDL statement.
2674Uses `idlwave-statement-match' to return a cons of (type . point) with
2675point the ending position where the type was determined.  Type is the
2676association from `idlwave-statement-match', i.e. the cons cell from the
2677list not just the type symbol.  Returns nil if not an identifiable
2678statement."
2679  (save-excursion
2680    ;; Skip whitespace within a statement which is spaces, tabs, continuations
2681    ;; and possibly comments
2682    (while (looking-at "[ \t]*\\$")
2683      (forward-line 1))
2684    (skip-chars-forward " \t")
2685    (let ((st idlwave-statement-match)
2686          (case-fold-search t))
2687      (while (and (not (looking-at (nth 0 (cdr (car st)))))
2688                  (setq st (cdr st))))
2689      (if st
2690          (append st (match-end 0))))))
2691
2692(defun idlwave-expand-equal (&optional before after is-action)
2693  "Pad `=' with spaces.
2694Two cases: Assignment statement, and keyword assignment.
2695Which case is determined using `idlwave-start-of-substatement' and
2696`idlwave-statement-type'.  The equal sign will be surrounded by BEFORE
2697and AFTER blanks.  If `idlwave-pad-keyword' is t then keyword assignment
2698is treated just like assignment statements.  When nil, spaces are
2699removed for keyword assignment.  Any other value keeps the current space
2700around the `='.  Limits in for loops are treated as keyword assignment.
2701
2702Starting with IDL 6.0, a number of op= assignments are available.
2703Since ambiguities of the form:
2704
2705r and= b
2706rand= b
2707
2708can occur, alphanumeric operator assignment will never be pre-padded,
2709only post-padded.  You must use a space before these to disambiguate
2710\(not just for padding, but for proper parsing by IDL too!).  Other
2711operators, such as ##=, ^=, etc., will be pre-padded.
2712
2713IS-ACTION is ignored.
2714
2715See `idlwave-surround'."
2716  (if idlwave-surround-by-blank
2717      (let
2718	  ((non-an-ops "\\(##\\|\\*\\|\\+\\|-\\|/\\|<\\|>\\|\\^\\)\\=")
2719	   (an-ops
2720	    "\\s-\\(AND\\|EQ\\|GE\\|GT\\|LE\\|LT\\|MOD\\|NE\\|OR\\|XOR\\)\\=")
2721	   (len 1))
2722
2723	(save-excursion
2724	  (let ((case-fold-search t))
2725	    (backward-char)
2726	    (if (or
2727		 (re-search-backward non-an-ops nil t)
2728		 ;; Why doesn't ##? work for both?
2729		 (re-search-backward "\\(#\\)\\=" nil t))
2730		(setq len (1+ (length (match-string 1))))
2731	      (when (re-search-backward an-ops nil t)
2732		;(setq begin nil) ; won't modify begin
2733		(setq len (1+ (length (match-string 1))))))))
2734
2735	(if (eq t idlwave-pad-keyword)
2736	    ;; Everything gets padded equally
2737	    (idlwave-surround before after len)
2738	  ;; Treating keywords/for variables specially...
2739	  (let ((st (save-excursion   ; To catch "for" variables
2740		      (idlwave-start-of-substatement t)
2741		      (idlwave-statement-type)))
2742		(what (save-excursion ; To catch keywords
2743			(skip-chars-backward "= \t")
2744			(nth 2 (idlwave-where)))))
2745	    (cond ((or (memq what '(function-keyword procedure-keyword))
2746		       (memq (caar st) '(for pdef)))
2747		   (cond
2748		    ((null idlwave-pad-keyword)
2749		     (idlwave-surround 0 0)
2750		     ) ; remove space
2751		    (t))) ; leave any spaces alone
2752		  (t (idlwave-surround before after len))))))))
2753
2754
2755(defun idlwave-indent-and-action (&optional arg)
2756  "Call `idlwave-indent-line' and do expand actions.
2757With prefix ARG non-nil, indent the entire sub-statement."
2758  (interactive "p")
2759  (save-excursion
2760    (if	(and idlwave-expand-generic-end
2761	     (re-search-backward "\\<\\(end\\)\\s-*\\="
2762				 (max 0 (- (point) 10)) t)
2763	     (looking-at "\\(end\\)\\([ \n\t]\\|\\'\\)"))
2764	(progn (goto-char (match-end 1))
2765	       ;;Expand the END abbreviation, just as RET or Space would have.
2766	       (if abbrev-mode (expand-abbrev)
2767		 (idlwave-show-begin)))))
2768  (when (and (not arg) current-prefix-arg)
2769    (setq arg current-prefix-arg)
2770    (setq current-prefix-arg nil))
2771  (if arg
2772      (idlwave-indent-statement)
2773    (idlwave-indent-line t)))
2774
2775(defun idlwave-indent-line (&optional expand)
2776  "Indent current IDL line as code or as a comment.
2777The actions in `idlwave-indent-action-table' are performed.
2778If the optional argument EXPAND is non-nil then the actions in
2779`idlwave-indent-expand-table' are performed."
2780  (interactive)
2781  ;; Move point out of left margin.
2782  (if (save-excursion
2783        (skip-chars-backward " \t")
2784        (bolp))
2785      (skip-chars-forward " \t"))
2786  (let ((mloc (point-marker)))
2787    (save-excursion
2788      (beginning-of-line)
2789      (if (looking-at idlwave-comment-line-start-skip)
2790          ;; Indentation for a line comment
2791          (progn
2792            (skip-chars-forward " \t")
2793            (idlwave-indent-left-margin (idlwave-comment-hook)))
2794        ;;
2795        ;; Code Line
2796        ;;
2797        ;; Before indenting, run action routines.
2798        ;;
2799        (if (and expand idlwave-do-actions)
2800            (mapc 'idlwave-do-action idlwave-indent-expand-table))
2801        ;;
2802        (if idlwave-do-actions
2803            (mapc 'idlwave-do-action idlwave-indent-action-table))
2804        ;;
2805        ;; No longer expand abbrevs on the line.  The user can do this
2806        ;; manually using expand-region-abbrevs.
2807        ;;
2808        ;; Indent for code line
2809        ;;
2810        (beginning-of-line)
2811        (if (or
2812             ;; a label line
2813             (looking-at (concat "^" idlwave-label "[ \t]*$"))
2814             ;; a batch command
2815             (looking-at "^[ \t]*@"))
2816            ;; leave flush left
2817            nil
2818          ;; indent the line
2819          (idlwave-indent-left-margin (idlwave-calculate-indent)))
2820        ;; Adjust parallel comment
2821	(end-of-line)
2822	(if (idlwave-in-comment)
2823	    ;; Emacs 21 is too smart with fill-column on comment indent
2824	    (let ((fill-column (if (fboundp 'comment-indent-new-line)
2825				   (1- (frame-width))
2826				 fill-column)))
2827	      (indent-for-comment)))))
2828    (goto-char mloc)
2829    ;; Get rid of marker
2830    (set-marker mloc nil)))
2831
2832(defun idlwave-do-action (action)
2833  "Perform an action repeatedly on a line.
2834ACTION is a list (REG . FUNC).  REG is a regular expression.  FUNC is
2835either a function name to be called with `funcall' or a list to be
2836evaluated with `eval'.  The action performed by FUNC should leave
2837point after the match for REG - otherwise an infinite loop may be
2838entered.  FUNC is always passed a final argument of `is-action', so it
2839can discriminate between being run as an action, or a key binding."
2840  (let ((action-key (car action))
2841        (action-routine (cdr action)))
2842    (beginning-of-line)
2843    (while (idlwave-look-at action-key)
2844      (if (listp action-routine)
2845          (eval (append action-routine '('is-action)))
2846        (funcall action-routine 'is-action)))))
2847
2848(defun idlwave-indent-to (col &optional min)
2849  "Indent from point with spaces until column COL.
2850Inserts space before markers at point."
2851  (if (not min) (setq min 0))
2852  (insert-before-markers
2853   (make-string (max min (- col (current-column))) ?\ )))
2854
2855(defun idlwave-indent-left-margin (col)
2856  "Indent the current line to column COL.
2857Indents such that first non-whitespace character is at column COL
2858Inserts spaces before markers at point."
2859  (save-excursion
2860    (beginning-of-line)
2861    (delete-horizontal-space)
2862    (idlwave-indent-to col)))
2863
2864(defun idlwave-indent-subprogram ()
2865  "Indent program unit which contains point."
2866  (interactive)
2867  (save-excursion
2868    (idlwave-end-of-statement)
2869    (idlwave-beginning-of-subprogram)
2870    (let ((beg (point)))
2871      (idlwave-forward-block)
2872      (message "Indenting subprogram...")
2873      (indent-region beg (point) nil))
2874    (message "Indenting subprogram...done.")))
2875
2876(defun idlwave-indent-statement ()
2877  "Indent current statement, including all continuation lines."
2878  (interactive)
2879  (save-excursion
2880    (idlwave-beginning-of-statement)
2881    (let ((beg (point)))
2882      (idlwave-end-of-statement)
2883      (indent-region beg (point) nil))))
2884
2885(defun idlwave-calculate-indent ()
2886  "Return appropriate indentation for current line as IDL code."
2887  (save-excursion
2888    (beginning-of-line)
2889    (cond
2890     ;; Check for beginning of unit - main (beginning of buffer), pro, or
2891     ;; function
2892     ((idlwave-look-at idlwave-begin-unit-reg)
2893      0)
2894     ;; Check for continuation line
2895     ((save-excursion
2896        (and (= (forward-line -1) 0)
2897             (idlwave-is-continuation-line)))
2898      (idlwave-calculate-cont-indent))
2899     ;; calculate indent based on previous and current statements
2900     (t (let* (beg-prev-pos
2901	       (the-indent
2902		;; calculate indent based on previous statement
2903		(save-excursion
2904		  (cond
2905		   ;; Beginning of file
2906		   ((prog1
2907			(idlwave-previous-statement)
2908		      (setq beg-prev-pos (point)))
2909		    0)
2910		   ;; Main block
2911		   ((idlwave-look-at idlwave-begin-unit-reg t)
2912		    (+ (idlwave-current-statement-indent)
2913		       idlwave-main-block-indent))
2914		   ;; Begin block
2915		   ((idlwave-look-at idlwave-begin-block-reg t)
2916		    (+ (idlwave-min-current-statement-indent)
2917		       idlwave-block-indent))
2918		   ;; End Block
2919		   ((idlwave-look-at idlwave-end-block-reg t)
2920		    (progn
2921		      ;; Match to the *beginning* of the block opener
2922		      (goto-char beg-prev-pos)
2923		      (idlwave-block-jump-out -1 'nomark) ; go to begin block
2924		      (idlwave-min-current-statement-indent)))
2925		      ;;		      idlwave-end-offset
2926		      ;;		      idlwave-block-indent))
2927
2928		   ;; Default to current indent
2929		   ((idlwave-current-statement-indent))))))
2930          ;; adjust the indentation based on the current statement
2931          (cond
2932           ;; End block
2933           ((idlwave-look-at idlwave-end-block-reg)
2934	    (+ the-indent idlwave-end-offset))
2935           (the-indent)))))))
2936
2937;;
2938;; Parentheses indent
2939;;
2940
2941(defun idlwave-calculate-paren-indent (beg-reg end-reg close-exp)
2942  "Calculate the continuation indent inside a paren group.
2943Returns a cons-cell with (open . indent), where open is the
2944location of the open paren."
2945  (let ((open (nth 1 (parse-partial-sexp beg-reg end-reg))))
2946    ;; Found an innermost open paren.
2947    (when open
2948      (goto-char open)
2949      ;; Line up with next word unless this is a closing paren.
2950      (cons open
2951	    (cond
2952	     ;; Plain Kernighan-style nested indent
2953	     (idlwave-indent-parens-nested
2954	      (+ idlwave-continuation-indent (idlwave-current-indent)))
2955
2956	     ;; This is a closed paren - line up under open paren.
2957	     (close-exp
2958	      (current-column))
2959
2960	     ;; Empty (or just comment) follows -- revert to basic indent
2961	     ((progn
2962		;; Skip paren
2963		(forward-char 1)
2964		(looking-at "[ \t$]*\\(;.*\\)?$"))
2965	      nil)
2966
2967	     ;; Line up with first word after any blank space
2968	     ((progn
2969		(skip-chars-forward " \t")
2970		(current-column))))))))
2971
2972(defun idlwave-calculate-cont-indent ()
2973  "Calculates the IDL continuation indent column from the previous statement.
2974Note that here previous statement usually means the beginning of the
2975current statement if this statement is a continuation of the previous
2976line.  Various special types of continuations, including assignments,
2977routine definitions, and parenthetical groupings, are treated separately."
2978  (save-excursion
2979    (let* ((case-fold-search t)
2980           (end-reg (progn (beginning-of-line) (point)))
2981	   (beg-last-statement (save-excursion (idlwave-previous-statement)
2982					       (point)))
2983           (beg-reg (progn (idlwave-start-of-substatement 'pre)
2984			   (if (eq (line-beginning-position) end-reg)
2985			       (goto-char beg-last-statement)
2986			     (point))))
2987	   (basic-indent (+ (idlwave-min-current-statement-indent end-reg)
2988			    idlwave-continuation-indent))
2989	   fancy-nonparen-indent fancy-paren-indent)
2990      (cond
2991       ;; Align then with its matching if, etc.
2992       ((let ((matchers '(("\\<if\\>" . "[ \t]*then")
2993			  ("\\<\\(if\\|end\\(if\\)?\\)\\>" . "[ \t]*else")
2994			  ("\\<\\(for\\|while\\)\\>" . "[ \t]*do")
2995			  ("\\<\\(repeat\\|end\\(rep\\)?\\)\\>" .
2996			   "[ \t]*until")
2997			  ("\\<case\\>" . "[ \t]*of")))
2998	      match cont-re)
2999	  (goto-char end-reg)
3000	  (and
3001	   (setq cont-re
3002		 (catch 'exit
3003		   (while (setq match (car matchers))
3004		     (if (looking-at (cdr match))
3005			 (throw 'exit (car match)))
3006		     (setq matchers (cdr matchers)))))
3007	   (idlwave-find-key cont-re -1 'nomark beg-last-statement)))
3008	(if (looking-at "end") ;; that one's special
3009	    (- (idlwave-current-indent)
3010	       (+ idlwave-block-indent idlwave-end-offset))
3011	  (idlwave-current-indent)))
3012
3013       ;; Indent in from the previous line for continuing statements
3014       ((let ((matchers '("\\<then\\>"
3015			  "\\<do\\>"
3016			  "\\<repeat\\>"
3017			  "\\<else\\>"))
3018	      match)
3019	  (catch 'exit
3020	    (goto-char end-reg)
3021	    (if (/= (forward-line -1) 0)
3022		(throw 'exit nil))
3023	    (while (setq match (car matchers))
3024	      (if (looking-at (concat ".*" match "[ \t]*\\$[ \t]*"
3025				      "\\(;.*\\)?$"))
3026		  (throw 'exit t))
3027	      (setq matchers (cdr matchers)))))
3028	(+ idlwave-continuation-indent (idlwave-current-indent)))
3029
3030       ;; Parenthetical indent, either traditional or Kernighan style
3031       ((setq fancy-paren-indent
3032	      (let* ((end-reg end-reg)
3033		    (close-exp (progn
3034				 (goto-char end-reg)
3035				 (skip-chars-forward " \t")
3036				 (looking-at "\\s)")))
3037		    indent-cons)
3038		(catch 'loop
3039		  (while (setq indent-cons (idlwave-calculate-paren-indent
3040					    beg-reg end-reg close-exp))
3041		    ;; First permitted containing paren
3042		    (if (or
3043			 idlwave-indent-to-open-paren
3044			 idlwave-indent-parens-nested
3045                         (null (cdr indent-cons))
3046			 (< (- (cdr indent-cons) basic-indent)
3047			    idlwave-max-extra-continuation-indent))
3048			(throw 'loop (cdr indent-cons)))
3049		    (setq end-reg (car indent-cons))))))
3050	fancy-paren-indent)
3051
3052       ;; A continued assignment, or procedure call/definition
3053       ((and
3054	 (> idlwave-max-extra-continuation-indent 0)
3055	 (setq fancy-nonparen-indent
3056	       (progn
3057		 (goto-char beg-reg)
3058		 (while (idlwave-look-at "&"))  ; skip continued statements
3059		 (cond
3060		  ;; A continued Procedure call or definition
3061		  ((progn
3062		     (idlwave-look-at "^[ \t]*\\(pro\\|function\\)") ;skip over
3063		     (looking-at "[ \t]*\\([a-zA-Z0-9.$_]+[ \t]*->[ \t]*\\)?[a-zA-Z][:a-zA-Z0-9$_]*[ \t]*\\(,\\)[ \t]*"))
3064		   (goto-char (match-end 0))
3065		   ;; Comment only, or blank line with "$"?  Basic indent.
3066		   (if (save-match-data (looking-at "[ \t$]*\\(;.*\\)?$"))
3067		       nil
3068		     (current-column)))
3069
3070		  ;; Continued assignment (with =):
3071		  ((catch 'assign ;
3072		     (while (looking-at "[^=\n\r]*\\(=\\)[ \t]*")
3073		       (goto-char (match-end 0))
3074		       (if (null (idlwave-what-function beg-reg))
3075			   (throw 'assign t))))
3076		   (unless (or
3077			    (idlwave-in-quote)
3078			    (looking-at "[ \t$]*\\(;.*\\)?$") ; use basic
3079			    (save-excursion
3080			      (goto-char beg-last-statement)
3081			      (eq (caar (idlwave-statement-type)) 'for)))
3082		     (current-column))))))
3083	 (< (- fancy-nonparen-indent basic-indent)
3084	    idlwave-max-extra-continuation-indent))
3085	(if fancy-paren-indent ;calculated but disallowed paren indent
3086	    (+ fancy-nonparen-indent idlwave-continuation-indent)
3087	  fancy-nonparen-indent))
3088
3089       ;; Basic indent, by default
3090       (t basic-indent)))))
3091
3092
3093
3094(defun idlwave-find-key (key-re &optional dir nomark limit)
3095  "Move to next match of the regular expression KEY-RE.
3096Matches inside comments or string constants will be ignored.
3097If DIR is negative, the search will be backwards.
3098At a successful match, the mark is pushed unless NOMARK is non-nil.
3099Searches are limited to LIMIT.
3100Searches are case-insensitive and use a special syntax table which
3101treats `$' and `_' as word characters.
3102Return value is the beginning of the match or (in case of failure) nil."
3103  (setq dir (or dir 0))
3104  (let ((case-fold-search t)
3105	(search-func (if (> dir 0) 're-search-forward 're-search-backward))
3106	found)
3107    (idlwave-with-special-syntax
3108     (save-excursion
3109       (catch 'exit
3110	 (while (funcall search-func key-re limit t)
3111	   (if (not (idlwave-quoted))
3112	       (throw 'exit (setq found (match-beginning 0)))
3113	     (if (or (and (> dir 0) (eobp))
3114		     (and (< dir 0) (bobp)))
3115		 (throw 'exit nil)))))))
3116    (if found
3117	(progn
3118	  (if (not nomark) (push-mark))
3119	  (goto-char found)
3120	  found)
3121      nil)))
3122
3123(defun idlwave-block-jump-out (&optional dir nomark)
3124  "When optional argument DIR is non-negative, move forward to end of
3125current block using the `idlwave-begin-block-reg' and `idlwave-end-block-reg'
3126regular expressions.  When DIR is negative, move backwards to block beginning.
3127Recursively calls itself to skip over nested blocks.  DIR defaults to
3128forward.  Calls `push-mark' unless the optional argument NOMARK is
3129non-nil.  Movement is limited by the start of program units because of
3130possibility of unbalanced blocks."
3131  (interactive "P")
3132  (or dir (setq dir 0))
3133  (let* ((here (point))
3134         (case-fold-search t)
3135         (limit (if (>= dir 0) (point-max) (point-min)))
3136         (block-limit (if (>= dir 0)
3137			  idlwave-begin-block-reg
3138			idlwave-end-block-reg))
3139         found
3140         (block-reg (concat idlwave-begin-block-reg "\\|"
3141			    idlwave-end-block-reg))
3142         (unit-limit (or (save-excursion
3143			   (if (< dir 0)
3144			       (idlwave-find-key
3145				idlwave-begin-unit-reg dir t limit)
3146			     (end-of-line)
3147			     (idlwave-find-key
3148			      idlwave-end-unit-reg dir t limit)))
3149			 limit)))
3150    (if (>= dir 0) (end-of-line)) ;Make sure we are in current block
3151    (if (setq found (idlwave-find-key  block-reg dir t unit-limit))
3152        (while (and found (looking-at block-limit))
3153          (if (>= dir 0) (forward-word-strictly 1))
3154          (idlwave-block-jump-out dir t)
3155          (setq found (idlwave-find-key block-reg dir t unit-limit))))
3156    (if (not nomark) (push-mark here))
3157    (if (not found) (goto-char unit-limit)
3158      (if (>= dir 0) (forward-word-strictly 1)))))
3159
3160(defun idlwave-min-current-statement-indent (&optional end-reg)
3161  "The minimum indent in the current statement."
3162  (idlwave-beginning-of-statement)
3163  (if (not (idlwave-is-continuation-line))
3164      (idlwave-current-indent)
3165    (let ((min (idlwave-current-indent)) comm-or-empty)
3166      (while (and (= (forward-line 1) 0)
3167		  (or (setq comm-or-empty (idlwave-is-comment-or-empty-line))
3168		      (idlwave-is-continuation-line))
3169		  (or (null end-reg) (< (point) end-reg)))
3170	(unless comm-or-empty (setq min (min min (idlwave-current-indent)))))
3171      (if (or comm-or-empty (and end-reg (>= (point) end-reg)))
3172	  min
3173	(min min (idlwave-current-indent))))))
3174
3175(defun idlwave-current-statement-indent (&optional last-line)
3176  "Return indentation of the current statement.
3177If in a statement, moves to beginning of statement before finding indent."
3178  (if last-line
3179      (idlwave-end-of-statement)
3180    (idlwave-beginning-of-statement))
3181  (idlwave-current-indent))
3182
3183(defun idlwave-current-indent ()
3184  "Return the column of the indentation of the current line.
3185Skips any whitespace.  Returns 0 if the end-of-line follows the whitespace."
3186  (save-excursion
3187    (beginning-of-line)
3188    (skip-chars-forward " \t")
3189    ;; if we are at the end of blank line return 0
3190    (cond ((eolp) 0)
3191          ((current-column)))))
3192
3193(defun idlwave-is-continuation-line ()
3194  "Test if current line is continuation line.
3195Blank or comment-only lines following regular continuation lines (with
3196`$') count as continuations too."
3197  (let (p)
3198    (save-excursion
3199      (or
3200       (idlwave-look-at "\\<\\$")
3201       (catch 'loop
3202	 (while (and (looking-at "^[ \t]*\\(;.*\\)?$")
3203		     (eq (forward-line -1) 0))
3204	   (if (setq p (idlwave-look-at "\\<\\$")) (throw 'loop p))))))))
3205
3206(defun idlwave-is-comment-line ()
3207  "Test if the current line is a comment line."
3208  (save-excursion
3209    (beginning-of-line 1)
3210    (looking-at "[ \t]*;")))
3211
3212(defun idlwave-is-comment-or-empty-line ()
3213  "Test if the current line is a comment line."
3214  (save-excursion
3215    (beginning-of-line 1)
3216    (looking-at "[ \t]*[;\n]")))
3217
3218(defun idlwave-look-at (regexp &optional cont beg)
3219  "Search current line from current point for REGEXP.
3220If optional argument CONT is non-nil, searches to the end of
3221the current statement.
3222If optional arg BEG is non-nil, search starts from the beginning of the
3223current statement.
3224Ignores matches that end in a comment or inside a string expression.
3225Returns point if successful, nil otherwise.
3226This function produces unexpected results if REGEXP contains quotes or
3227a comment delimiter.  The search is case insensitive.
3228If successful leaves point after the match, otherwise, does not move point."
3229  (let ((here (point))
3230        (case-fold-search t)
3231        (eos (save-excursion
3232	       (if cont (idlwave-end-of-statement) (end-of-line))
3233	       (point)))
3234        found)
3235    (idlwave-with-special-syntax
3236     (if beg (idlwave-beginning-of-statement))
3237     (while (and (setq found (re-search-forward regexp eos t))
3238		 (idlwave-quoted))))
3239    (if (not found) (goto-char here))
3240    found))
3241
3242(defun idlwave-fill-paragraph (&optional nohang)
3243  "Fill paragraphs in comments.
3244A paragraph is made up of all contiguous lines having the same comment
3245leader (the leading whitespace before the comment delimiter and the
3246comment delimiter).  In addition, paragraphs are separated by blank
3247line comments.  The indentation is given by the hanging indent of the
3248first line, otherwise by the minimum indentation of the lines after
3249the first line.  The indentation of the first line does not change.
3250Does not effect code lines.  Does not fill comments on the same line
3251with code.  The hanging indent is given by the end of the first match
3252matching `idlwave-hang-indent-regexp' on the paragraph's first line.
3253If the optional argument NOHANG is non-nil then the hanging indent is
3254ignored."
3255  (interactive "P")
3256  ;; check if this is a line comment
3257  (if (save-excursion
3258        (beginning-of-line)
3259        (skip-chars-forward " \t")
3260        (looking-at comment-start))
3261      (let
3262          ((indent 999)
3263           pre here diff fill-prefix-reg bcl first-indent
3264           hang start end)
3265        ;; Change tabs to spaces in the surrounding paragraph.
3266        ;; The surrounding paragraph will be the largest containing block of
3267        ;; contiguous line comments. Thus, we may be changing tabs in
3268        ;; a much larger area than is needed, but this is the easiest
3269        ;; brute force way to do it.
3270        ;;
3271        ;; This has the undesirable side effect of replacing the tabs
3272        ;; permanently without the user's request or knowledge.
3273        (save-excursion
3274          (backward-paragraph)
3275          (setq start (point)))
3276        (save-excursion
3277          (forward-paragraph)
3278          (setq end (point)))
3279        (untabify start end)
3280        ;;
3281        (setq here (point))
3282        (beginning-of-line)
3283        (setq bcl (point))
3284        (re-search-forward (concat "^[ \t]*" comment-start "+")
3285			   (point-at-eol) t)
3286        ;; Get the comment leader on the line and its length
3287        (setq pre (current-column))
3288        ;; the comment leader is the indentation plus exactly the
3289        ;; number of consecutive ";".
3290        (setq fill-prefix-reg
3291              (concat
3292               (setq fill-prefix
3293                     (regexp-quote (buffer-substring (point-at-bol) (point))))
3294               "[^;]"))
3295
3296        ;; Mark the beginning and end of the paragraph
3297        (goto-char bcl)
3298        (while (and (looking-at fill-prefix-reg)
3299                    (not (looking-at paragraph-separate))
3300                    (not (bobp)))
3301          (forward-line -1))
3302        ;; Move to first line of paragraph
3303        (if (/= (point) bcl)
3304            (forward-line 1))
3305        (setq start (point))
3306        (goto-char bcl)
3307        (while (and (looking-at fill-prefix-reg)
3308                    (not (looking-at paragraph-separate))
3309                    (not (eobp)))
3310          (forward-line 1))
3311        (beginning-of-line)
3312        (if (or (not (looking-at fill-prefix-reg))
3313                (looking-at paragraph-separate))
3314            (forward-line -1))
3315        (end-of-line)
3316        ;; if at end of buffer add a newline (need this because
3317        ;; fill-region needs END to be at the beginning of line after
3318        ;; the paragraph or it will add a line).
3319        (if (eobp)
3320            (progn (insert ?\n) (backward-char 1)))
3321        ;; Set END to the beginning of line after the paragraph
3322        ;; END is calculated as distance from end of buffer
3323        (setq end (- (point-max) (point) 1))
3324        ;;
3325        ;; Calculate the indentation for the paragraph.
3326        ;;
3327        ;; In the following while statements, after one iteration
3328        ;; point will be at the beginning of a line in which case
3329        ;; the while will not be executed for the
3330        ;; the first paragraph line and thus will not affect the
3331        ;; indentation.
3332        ;;
3333        ;; First check to see if indentation is based on hanging indent.
3334        (if (and (not nohang) idlwave-hanging-indent
3335                 (setq hang
3336                       (save-excursion
3337                         (goto-char start)
3338                         (idlwave-calc-hanging-indent))))
3339            ;; Adjust lines of paragraph by inserting spaces so that
3340            ;; each line's indent is at least as great as the hanging
3341            ;; indent. This is needed for fill-paragraph to work with
3342            ;; a fill-prefix.
3343            (progn
3344              (setq indent hang)
3345              (beginning-of-line)
3346              (while (> (point) start)
3347                (re-search-forward comment-start-skip (point-at-eol) t)
3348                (if (> (setq diff (- indent (current-column))) 0)
3349                    (progn
3350                      (if (>= here (point))
3351                          ;; adjust the original location for the
3352                          ;; inserted text.
3353                          (setq here (+ here diff)))
3354                      (insert (make-string diff ?\ ))))
3355                (forward-line -1))
3356              )
3357
3358          ;; No hang. Instead find minimum indentation of paragraph
3359          ;; after first line.
3360          ;; For the following while statement, since START is at the
3361          ;; beginning of line and END is at the end of line
3362          ;; point is greater than START at least once (which would
3363          ;; be the case for a single line paragraph).
3364          (while (> (point) start)
3365            (beginning-of-line)
3366            (setq indent
3367                  (min indent
3368                       (progn
3369                         (re-search-forward comment-start-skip (point-at-eol) t)
3370                         (current-column))))
3371            (forward-line -1)))
3372        (setq fill-prefix (concat fill-prefix
3373                                  (make-string (- indent pre)
3374                                               ?\ )))
3375        ;; first-line indent
3376        (setq first-indent
3377              (max
3378               (progn
3379                 (re-search-forward comment-start-skip (point-at-eol) t)
3380                 (current-column))
3381               indent))
3382
3383        ;; try to keep point at its original place
3384        (goto-char here)
3385
3386        ;; In place of the more modern fill-region-as-paragraph, a hack
3387        ;; to keep whitespace untouched on the first line within the
3388        ;; indent length and to preserve any indent on the first line
3389        ;; (first indent).
3390        (save-excursion
3391          (setq diff
3392                (buffer-substring start (+ start first-indent -1)))
3393          (subst-char-in-region start (+ start first-indent -1) ?\  ?~ nil)
3394          (fill-region-as-paragraph
3395           start
3396           (- (point-max) end)
3397           (current-justification)
3398           nil)
3399          (delete-region start (+ start first-indent -1))
3400          (goto-char start)
3401          (insert diff))
3402        ;; When we want the point at the beginning of the comment
3403        ;; body fill-region will put it at the beginning of the line.
3404        (if (bolp) (skip-chars-forward (concat " \t" comment-start)))
3405        (setq fill-prefix nil))))
3406
3407(defun idlwave-calc-hanging-indent ()
3408  "Calculate the position of the hanging indent for the comment paragraph.
3409The hanging indent position is given by the first match with the
3410`idlwave-hang-indent-regexp'.  If `idlwave-use-last-hang-indent' is
3411non-nil then use last occurrence matching `idlwave-hang-indent-regexp'
3412on the line.
3413If not found returns nil."
3414  (if idlwave-use-last-hang-indent
3415      (save-excursion
3416        (end-of-line)
3417        (if (re-search-backward idlwave-hang-indent-regexp (point-at-bol) t)
3418            (+ (current-column) (length idlwave-hang-indent-regexp))))
3419    (save-excursion
3420      (beginning-of-line)
3421      (if (re-search-forward idlwave-hang-indent-regexp (point-at-eol) t)
3422          (current-column)))))
3423
3424(defun idlwave-auto-fill ()
3425  "Called to break lines in auto fill mode.
3426Only fills non-comment lines if `idlwave-fill-comment-line-only' is
3427non-nil.  Places a continuation character at the end of the line if
3428not in a comment.  Splits strings with IDL concatenation operator `+'
3429if `idlwave-auto-fill-split-string' is non-nil."
3430  (if (<= (current-column) fill-column)
3431      nil                             ; do not to fill
3432    (if (or (not idlwave-fill-comment-line-only)
3433	    (save-excursion
3434	      ;; Check for comment line
3435	      (beginning-of-line)
3436	      (looking-at idlwave-comment-line-start-skip)))
3437	(let (beg)
3438	  (idlwave-indent-line)
3439	  ;; Prevent actions do-auto-fill which calls indent-line-function.
3440	  (let (idlwave-do-actions
3441		(paragraph-separate ".")
3442		(fill-nobreak-predicate
3443		 (if (and (idlwave-in-quote)
3444			  idlwave-auto-fill-split-string)
3445		     (lambda () ;; We'll need 5 spaces for " ' + $"
3446		       (<= (- fill-column (current-column)) 5)
3447		       ))))
3448	    (do-auto-fill))
3449	  (save-excursion
3450	    (end-of-line 0)
3451	    ;; Indent the split line
3452	    (idlwave-indent-line))
3453	  (if (save-excursion
3454		(beginning-of-line)
3455		(looking-at idlwave-comment-line-start-skip))
3456	      ;; A continued line comment
3457	      ;; We treat continued line comments as part of a comment
3458	      ;; paragraph. So we check for a hanging indent.
3459	      (if idlwave-hanging-indent
3460		  (let ((here (- (point-max) (point)))
3461			(indent
3462			 (save-excursion
3463			   (forward-line -1)
3464			   (idlwave-calc-hanging-indent))))
3465		    (when indent
3466		      ;; Remove whitespace between comment delimiter and
3467		      ;; text, insert spaces for appropriate indentation.
3468		      (beginning-of-line)
3469		      (re-search-forward comment-start-skip (point-at-eol) t)
3470		      (delete-horizontal-space)
3471		      (idlwave-indent-to indent)
3472		      (goto-char (- (point-max) here)))))
3473	    ;; Split code or comment?
3474	    (if (save-excursion
3475		  (end-of-line 0)
3476		  (idlwave-in-comment))
3477		;; Splitting a non-full-line comment.
3478		;; Insert the comment delimiter from split line
3479		(progn
3480		  (save-excursion
3481		    (beginning-of-line)
3482		    (skip-chars-forward " \t")
3483		    ;; Insert blank to keep off beginning of line
3484		    (insert " "
3485			    (save-excursion
3486			      (forward-line -1)
3487			      (buffer-substring (idlwave-goto-comment)
3488						(progn
3489						  (skip-chars-forward "; ")
3490						  (point))))))
3491		  (idlwave-indent-line))
3492	      ;; Split code line - add continuation character
3493	      (save-excursion
3494		(end-of-line 0)
3495		;; Check to see if we split a string
3496		(if (and (setq beg (idlwave-in-quote))
3497			 idlwave-auto-fill-split-string)
3498		    ;; Split the string and concatenate.
3499		    ;; The first extra space is for the space
3500		    ;; the line was split. That space was removed.
3501		    (insert " " (char-after beg) " +"))
3502		(insert " $"))
3503	      (if beg
3504		  (if idlwave-auto-fill-split-string
3505		      ;; Make the second part of continued string
3506		      (save-excursion
3507			(beginning-of-line)
3508			(skip-chars-forward " \t")
3509			(insert (char-after beg)))
3510		    ;; Warning
3511		    (beep)
3512		    (message "Warning: continuation inside a string.")))
3513	      ;; Although do-auto-fill (via indent-new-comment-line) calls
3514	      ;; idlwave-indent-line for the new line, re-indent again
3515	      ;; because of the addition of the continuation character.
3516	      (idlwave-indent-line))
3517	    )))))
3518
3519(defun idlwave-auto-fill-mode (arg)
3520  "Toggle auto-fill mode for IDL mode.
3521With arg, turn auto-fill mode on if arg is positive.
3522In auto-fill mode, inserting a space at a column beyond `fill-column'
3523automatically breaks the line at a previous space."
3524  (interactive "P")
3525  (prog1 (set idlwave-fill-function
3526              (if (if (null arg)
3527                      (not (symbol-value idlwave-fill-function))
3528                    (> (prefix-numeric-value arg) 0))
3529                  'idlwave-auto-fill
3530                nil))
3531    ;; update mode-line
3532    (set-buffer-modified-p (buffer-modified-p))))
3533
3534;(defun idlwave-fill-routine-call ()
3535;  "Fill a routine definition or statement, indenting appropriately."
3536;  (let ((where (idlwave-where)))))
3537
3538
3539(defun idlwave-doc-header (&optional nomark)
3540  "Insert a documentation header at the beginning of the unit.
3541Inserts the value of the variable `idlwave-file-header'.  Sets mark
3542before moving to do insertion unless the optional prefix argument
3543NOMARK is non-nil."
3544  (interactive "P")
3545  (or nomark (push-mark))
3546  ;; make sure we catch the current line if it begins the unit
3547  (if idlwave-header-to-beginning-of-file
3548      (goto-char (point-min))
3549    (end-of-line)
3550    (idlwave-beginning-of-subprogram)
3551    (beginning-of-line)
3552    ;; skip function or procedure line
3553    (if (idlwave-look-at "\\<\\(pro\\|function\\)\\>")
3554	(progn
3555	  (idlwave-end-of-statement)
3556	  (if (> (forward-line 1) 0) (insert "\n")))))
3557  (let ((pos (point)))
3558    (if idlwave-file-header
3559	(cond ((car idlwave-file-header)
3560	       (insert-file-contents (car idlwave-file-header)))
3561	      ((stringp (car (cdr idlwave-file-header)))
3562	       (insert (car (cdr idlwave-file-header))))))
3563    (goto-char pos)))
3564
3565(defun idlwave-default-insert-timestamp ()
3566  "Default timestamp insertion function."
3567  (insert (current-time-string))
3568  (insert ", " (user-full-name))
3569  (if (boundp 'user-mail-address)
3570      (insert " <" user-mail-address ">")
3571    (insert " <" (user-login-name) "@" (system-name) ">"))
3572  ;; Remove extra spaces from line
3573  (idlwave-fill-paragraph)
3574  ;; Insert a blank line comment to separate from the date entry -
3575  ;; will keep the entry from flowing onto date line if re-filled.
3576  (insert "\n;\n;\t\t"))
3577
3578(defun idlwave-doc-modification ()
3579  "Insert a brief modification log at the beginning of the current program.
3580Looks for an occurrence of the value of user variable
3581`idlwave-doc-modifications-keyword' if non-nil.  Inserts time and user
3582name and places the point for the user to add a log.  Before moving, saves
3583location on mark ring so that the user can return to previous point."
3584  (interactive)
3585  (push-mark)
3586  (let* (beg end)
3587    (if (and (or (re-search-backward idlwave-doclib-start nil t)
3588		 (progn
3589		   (goto-char (point-min))
3590		   (re-search-forward idlwave-doclib-start nil t)))
3591	     (setq beg (match-beginning 0))
3592	     (re-search-forward idlwave-doclib-end nil t)
3593	     (setq end (match-end 0)))
3594	(progn
3595	  (goto-char beg)
3596	  (if (re-search-forward
3597	       (concat idlwave-doc-modifications-keyword ":")
3598	       end t)
3599	      (end-of-line)
3600	    (goto-char end)
3601	    (end-of-line -1)
3602	    (insert "\n" comment-start "\n")
3603	    (insert comment-start " " idlwave-doc-modifications-keyword ":"))
3604	  (insert "\n;\n;\t")
3605	  (run-hooks 'idlwave-timestamp-hook))
3606      (error "No valid DOCLIB header"))))
3607
3608
3609;; CJC 3/16/93
3610;; Interface to expand-region-abbrevs which did not work when the
3611;; abbrev hook associated with an abbrev moves point backwards
3612;; after abbrev expansion, e.g., as with the abbrev '.n'.
3613;; The original would enter an infinite loop in attempting to expand
3614;; .n (it would continually expand and unexpand the abbrev without expanding
3615;; because the point would keep going back to the beginning of the
3616;; abbrev instead of to the end of the abbrev). We now keep the
3617;; abbrev hook from moving backwards.
3618;;;
3619(defun idlwave-expand-region-abbrevs (start end)
3620  "Expand each abbrev occurrence in the region.
3621Calling from a program, arguments are START END."
3622  (interactive "r")
3623  (save-excursion
3624    (goto-char (min start end))
3625    (let ((idlwave-show-block nil)          ;Do not blink
3626          (idlwave-abbrev-move nil))        ;Do not move
3627      (expand-region-abbrevs start end 'noquery))))
3628
3629(defun idlwave-quoted ()
3630  "Return t if point is in a comment or quoted string.
3631Returns nil otherwise."
3632  (and (or (idlwave-in-comment) (idlwave-in-quote)) t))
3633
3634(defun idlwave-in-quote ()
3635  "Return location of the opening quote
3636if point is in a IDL string constant, nil otherwise.
3637Ignores comment delimiters on the current line.
3638Properly handles nested quotation marks and octal
3639constants - a double quote followed by an octal digit."
3640;; Treat an octal inside an apostrophe to be a normal string. Treat a
3641;; double quote followed by an octal digit to be an octal constant
3642;; rather than a string. Therefore, there is no terminating double
3643;; quote.
3644  (save-excursion
3645    ;; Because single and double quotes can quote each other we must
3646    ;; search for the string start from the beginning of line.
3647    (let* ((start (point))
3648           (eol (point-at-eol))
3649           (bq (progn (beginning-of-line) (point)))
3650           (endq (point))
3651           (data (match-data))
3652           delim
3653           found)
3654      (while  (< endq start)
3655	;; Find string start
3656	;; Don't find an octal constant beginning with a double quote
3657	(if (re-search-forward "[\"']" eol 'lim)
3658	    ;; Find the string end.
3659	    ;; In IDL, two consecutive delimiters after the start of a
3660	    ;; string act as an
3661	    ;; escape for the delimiter in the string.
3662	    ;; Two consecutive delimiters alone (i.e., not after the
3663	    ;; start of a string) is the null string.
3664	    (progn
3665	      ;; Move to position after quote
3666	      (goto-char (1+ (match-beginning 0)))
3667	      (setq bq (1- (point)))
3668	      ;; Get the string delimiter
3669	      (setq delim (char-to-string (preceding-char)))
3670	      ;; Check for null string
3671	      (if (looking-at delim)
3672		  (progn (setq endq (point)) (forward-char 1))
3673		;; Look for next unpaired delimiter
3674		(setq found (search-forward delim eol 'lim))
3675		(while (looking-at delim)
3676		  (forward-char 1)
3677		  (setq found (search-forward delim eol 'lim)))
3678		(setq endq (if found (1- (point)) (point)))
3679		))
3680	  (progn (setq bq (point)) (setq endq (point)))))
3681      (store-match-data data)
3682      ;; return string beginning position or nil
3683      (if (> start bq) bq))))
3684
3685(defun idlwave-is-pointer-dereference (&optional limit)
3686  "Determine if the character after point is a pointer dereference *."
3687  (and
3688   (eq (char-after) ?\*)
3689   (not (idlwave-in-quote))
3690   (save-excursion
3691     (forward-char)
3692     (re-search-backward (concat "\\(" idlwave-idl-keywords
3693                                 "\\|[-[(*+/=,^><]\\)\\s-*\\*") limit t))))
3694
3695
3696;; Statement templates
3697
3698;; Replace these with a general template function, something like
3699;; expand.el (I think there was also something with a name similar to
3700;; dmacro.el)
3701
3702(defun idlwave-template (s1 s2 &optional prompt noindent)
3703  "Build a template with optional prompt expression.
3704
3705Opens a line if point is not followed by a newline modulo intervening
3706whitespace.  S1 and S2 are strings.  S1 is inserted at point followed
3707by S2.  Point is inserted between S1 and S2.  The case of S1 and S2 is
3708adjusted according to `idlwave-abbrev-change-case'.  If optional
3709argument PROMPT is a string then it is displayed as a message in the
3710minibuffer.  The PROMPT serves as a reminder to the user of an
3711expression to enter.
3712
3713The lines containing S1 and S2 are reindented using `indent-region'
3714unless the optional second argument NOINDENT is non-nil."
3715  (if (derived-mode-p 'idlwave-shell-mode)
3716      ;; This is a gross hack to avoid template abbrev expansion
3717      ;; in the shell.  FIXME: This is a dirty hack.
3718      (if (and (eq this-command 'self-insert-command)
3719	       (equal last-abbrev-location (point)))
3720	  (insert last-abbrev-text)
3721	(error "No templates in idlwave-shell"))
3722    (cond ((eq idlwave-abbrev-change-case 'down)
3723	   (setq s1 (downcase s1) s2 (downcase s2)))
3724	  (idlwave-abbrev-change-case
3725	   (setq s1 (upcase s1) s2 (upcase s2))))
3726    (let ((beg (point-at-bol))
3727	  end)
3728      (if (not (looking-at "\\s-*\n"))
3729	  (open-line 1))
3730      (insert s1)
3731      (save-excursion
3732	(insert s2)
3733	(setq end (point)))
3734      (if (not noindent)
3735	  (indent-region beg end nil))
3736      (if (stringp prompt)
3737	  (message "%s" prompt)))))
3738
3739(defun idlwave-rw-case (string)
3740  "Make STRING have the case required by `idlwave-reserved-word-upcase'."
3741  (if idlwave-reserved-word-upcase
3742      (upcase string)
3743    string))
3744
3745(defun idlwave-elif ()
3746  "Build skeleton IDL if-else block."
3747  (interactive)
3748  (idlwave-template
3749   (idlwave-rw-case "if")
3750   (idlwave-rw-case " then begin\n\nendif else begin\n\nendelse")
3751   "Condition expression"))
3752
3753(defun idlwave-case ()
3754  "Build skeleton IDL case statement."
3755  (interactive)
3756  (idlwave-template
3757   (idlwave-rw-case "case")
3758   (idlwave-rw-case " of\n\nendcase")
3759   "Selector expression"))
3760
3761(defun idlwave-switch ()
3762  "Build skeleton IDL switch statement."
3763  (interactive)
3764  (idlwave-template
3765   (idlwave-rw-case "switch")
3766   (idlwave-rw-case " of\n\nendswitch")
3767   "Selector expression"))
3768
3769(defun idlwave-for ()
3770  "Build skeleton IDL loop statement."
3771  (interactive)
3772  (idlwave-template
3773   (idlwave-rw-case "for")
3774   (idlwave-rw-case " do begin\n\nendfor")
3775   "Loop expression"))
3776
3777(defun idlwave-if ()
3778  "Build skeleton IDL if statement."
3779  (interactive)
3780  (idlwave-template
3781   (idlwave-rw-case "if")
3782   (idlwave-rw-case " then begin\n\nendif")
3783   "Scalar logical expression"))
3784
3785(defun idlwave-procedure ()
3786  (interactive)
3787  (idlwave-template
3788   (idlwave-rw-case "pro")
3789   (idlwave-rw-case "\n\nreturn\nend")
3790   "Procedure name"))
3791
3792(defun idlwave-function ()
3793  (interactive)
3794  (idlwave-template
3795   (idlwave-rw-case "function")
3796   (idlwave-rw-case "\n\nreturn\nend")
3797   "Function name"))
3798
3799(defun idlwave-repeat ()
3800  (interactive)
3801  (idlwave-template
3802   (idlwave-rw-case "repeat begin\n\nendrep until")
3803   (idlwave-rw-case "")
3804   "Exit condition"))
3805
3806(defun idlwave-while ()
3807  (interactive)
3808  (idlwave-template
3809   (idlwave-rw-case "while")
3810   (idlwave-rw-case " do begin\n\nendwhile")
3811   "Entry condition"))
3812
3813(defun idlwave-split-string (string &optional pattern)
3814  "Return a list of substrings of STRING which are separated by PATTERN.
3815If PATTERN is omitted, it defaults to \"[ \\f\\t\\n\\r\\v]+\"."
3816  (or pattern
3817      (setq pattern "[ \f\t\n\r\v]+"))
3818  (let (parts (start 0))
3819    (while (string-match pattern string start)
3820      (setq parts (cons (substring string start (match-beginning 0)) parts)
3821	    start (match-end 0)))
3822    (nreverse (cons (substring string start) parts))))
3823
3824(defun idlwave-replace-string (string replace_string replace_with)
3825  (let* ((start 0)
3826	 (last (length string))
3827	 (ret_string "")
3828	 end)
3829    (while (setq end (string-match replace_string string start))
3830      (setq ret_string
3831	    (concat ret_string (substring string start end) replace_with))
3832      (setq start (match-end 0)))
3833    (setq ret_string (concat ret_string (substring string start last)))))
3834
3835(defun idlwave-get-buffer-visiting (file)
3836  ;; Return the buffer currently visiting FILE
3837  (cond
3838   ((boundp 'find-file-compare-truenames) ; XEmacs
3839    (let ((find-file-compare-truenames t))
3840      (get-file-buffer file)))
3841   ((fboundp 'find-buffer-visiting)       ; Emacs
3842    (find-buffer-visiting file))
3843   (t (error "This should not happen (idlwave-get-buffer-visiting)"))))
3844
3845(defvar idlwave-outlawed-buffers nil
3846  "List of buffers pulled up by IDLWAVE for special reasons.
3847Buffers in this list may be killed by `idlwave-kill-autoloaded-buffers'.")
3848
3849(defun idlwave-find-file-noselect (file &optional why)
3850  ;; Return a buffer visiting file.
3851  (or (idlwave-get-buffer-visiting file)
3852      (let ((buf (find-file-noselect file)))
3853	(if why (add-to-list 'idlwave-outlawed-buffers (cons buf why)))
3854	buf)))
3855
3856(defun idlwave-kill-autoloaded-buffers ()
3857  "Kill buffers created automatically by IDLWAVE.
3858Function prompts for a letter to identify the buffers to kill.
3859Possible letters are:
3860
3861f    Buffers created by the command \\[idlwave-find-module] or mouse
3862     clicks in the routine info window.
3863s    Buffers created by the IDLWAVE Shell to display where execution
3864     stopped or an error was found.
3865a    Both of the above.
3866
3867Buffers containing unsaved changes require confirmation before they are killed."
3868  (interactive)
3869  (if (null idlwave-outlawed-buffers)
3870      (error "No IDLWAVE-created buffers available")
3871    (princ (format "Kill IDLWAVE-created buffers: [f]ind source(%d), [s]hell display(%d), [a]ll ? "
3872		   (idlwave-count-outlawed-buffers 'find)
3873		   (idlwave-count-outlawed-buffers 'shell)))
3874    (let ((c (read-char)))
3875      (cond
3876       ((member c '(?f ?\C-f))
3877	(idlwave-do-kill-autoloaded-buffers 'find))
3878       ((member c '(?s ?\C-s))
3879	(idlwave-do-kill-autoloaded-buffers 'shell))
3880       ((member c '(?a ?\C-a))
3881	(idlwave-do-kill-autoloaded-buffers t))
3882       (t (error "Abort"))))))
3883
3884(defun idlwave-count-outlawed-buffers (tag)
3885  "How many outlawed buffers have tag TAG?"
3886  (length (delq nil
3887		(mapcar
3888		 (lambda (x) (eq (cdr x) tag))
3889		 idlwave-outlawed-buffers))))
3890
3891(defun idlwave-do-kill-autoloaded-buffers (&rest reasons)
3892  "Kill all buffers pulled up by IDLWAVE matching REASONS."
3893  (let* ((list (copy-sequence idlwave-outlawed-buffers))
3894	 (cnt 0)
3895	 entry)
3896    (while (setq entry (pop list))
3897      (if (buffer-live-p (car entry))
3898	  (and (or (memq t reasons)
3899		   (memq (cdr entry) reasons))
3900	       (kill-buffer (car entry))
3901	       (cl-incf cnt)
3902	       (setq idlwave-outlawed-buffers
3903		     (delq entry idlwave-outlawed-buffers)))
3904	(setq idlwave-outlawed-buffers
3905	      (delq entry idlwave-outlawed-buffers))))
3906    (message "%d buffer%s killed" cnt (if (= cnt 1) "" "s"))))
3907
3908(defun idlwave-revoke-license-to-kill ()
3909  "Remove BUFFER from the buffers which may be killed.
3910Killing would be done by `idlwave-do-kill-autoloaded-buffers'.
3911Intended for `after-save-hook'."
3912  (let* ((buf (current-buffer))
3913	 (entry (assq buf idlwave-outlawed-buffers)))
3914    ;; Revoke license
3915    (if entry
3916	(setq idlwave-outlawed-buffers
3917	      (delq entry idlwave-outlawed-buffers)))
3918    ;; Remove this function from the hook.
3919    (remove-hook 'after-save-hook 'idlwave-revoke-license-to-kill 'local)))
3920
3921(defvar idlwave-path-alist)
3922(defun idlwave-locate-lib-file (file)
3923  ;; Find FILE on the scanned lib path and return a buffer visiting it
3924  (let* ((dirs idlwave-path-alist)
3925	 dir efile)
3926    (catch 'exit
3927      (while (setq dir (car (pop dirs)))
3928	(if (file-regular-p
3929	     (setq efile (expand-file-name file dir)))
3930	    (throw 'exit efile))))))
3931
3932(defun idlwave-expand-lib-file-name (file)
3933  ;; Find FILE on the scanned lib path and return a buffer visiting it
3934  ;; This is for, e.g., finding source with no user catalog
3935  (cond
3936   ((null file) nil)
3937   ((file-name-absolute-p file) file)
3938   (t (idlwave-locate-lib-file file))))
3939
3940(defun idlwave-make-tags ()
3941  "Create the IDL tags file IDLTAGS in the current directory from
3942the list of directories specified in the minibuffer.  Directories may be
3943for example: . /usr/local/rsi/idl/lib.  All the subdirectories of the
3944specified top directories are searched if the directory name is prefixed
3945by @.  Specify @ directories with care, it may take a long, long time if
3946you specify /."
3947  (interactive)
3948  (let (directory directories cmd append status numdirs dir getsubdirs
3949		  buffer save_buffer files numfiles item errbuf)
3950
3951    ;;
3952    ;; Read list of directories
3953    (setq directory (read-string "Tag Directories: " "."))
3954    (setq directories (idlwave-split-string directory "[ \t]+"))
3955    ;;
3956    ;; Set etags command, vars
3957    (setq cmd "etags --output=IDLTAGS --language=none --regex='/[
3958\\t]*[pP][Rr][Oo][ \\t]+\\([^ \\t,]+\\)/' --regex='/[
3959\\t]*[Ff][Uu][Nn][Cc][Tt][Ii][Oo][Nn][ \\t]+\\([^ \\t,]+\\)/' ")
3960    (setq append " ")
3961    (setq status 0)
3962    ;;
3963    ;; For each directory
3964    (setq numdirs 0)
3965    (setq dir (nth numdirs directories))
3966    (while (and dir)
3967      ;;
3968      ;; Find the subdirectories
3969      (if (string-match "^[@]\\(.+\\)$" dir)
3970	  (setq getsubdirs t) (setq getsubdirs nil))
3971      (if (and getsubdirs) (setq dir (substring dir 1 (length dir))))
3972      (setq dir (expand-file-name dir))
3973      (if (file-directory-p dir)
3974	  (progn
3975	    (if (and getsubdirs)
3976		(progn
3977		  (setq buffer (get-buffer-create "*idltags*"))
3978		  (call-process "sh" nil buffer nil "-c"
3979				(concat "find " dir " -type d -print"))
3980		  (setq save_buffer (current-buffer))
3981		  (set-buffer buffer)
3982		  (setq files (idlwave-split-string
3983			       (idlwave-replace-string
3984				(buffer-substring 1 (point-max))
3985				"\n" "/*.pro ")
3986			       "[ \t]+"))
3987		  (set-buffer save_buffer)
3988		  (kill-buffer buffer))
3989	      (setq files (list (concat dir "/*.pro"))))
3990	    ;;
3991	    ;; For each subdirectory
3992	    (setq numfiles 0)
3993	    (setq item (nth numfiles files))
3994	    (while (and item)
3995	      ;;
3996	      ;; Call etags
3997	      (if (not (string-match "^[ \\t]*$" item))
3998		  (progn
3999		    (message "%s" (concat "Tagging " item "..."))
4000		    (setq errbuf (get-buffer-create "*idltags-error*"))
4001		    (setq status (+ status
4002				    (if (eq 0 (call-process
4003					       "sh" nil errbuf nil "-c"
4004					       (concat cmd append item)))
4005					0
4006  	                                1)))
4007		    ;;
4008		    ;; Append additional tags
4009		    (setq append " --append ")
4010		    (setq numfiles (1+ numfiles))
4011		    (setq item (nth numfiles files)))
4012		(progn
4013		  (setq numfiles (1+ numfiles))
4014		  (setq item (nth numfiles files))
4015		  )))
4016
4017	    (setq numdirs (1+ numdirs))
4018	    (setq dir (nth numdirs directories)))
4019	(progn
4020	  (setq numdirs (1+ numdirs))
4021	  (setq dir (nth numdirs directories)))))
4022
4023    (setq errbuf (get-buffer-create "*idltags-error*"))
4024    (if (= status 0)
4025	(kill-buffer errbuf))
4026    (message "")
4027    ))
4028
4029(defun idlwave-toggle-comment-region (beg end &optional n)
4030  "Comment the lines in the region if the first non-blank line is
4031commented, and conversely, uncomment region.  If optional prefix arg
4032N is non-nil, then for N positive, add N comment delimiters or for N
4033negative, remove N comment delimiters.
4034Uses `comment-region' which does not place comment delimiters on
4035blank lines."
4036  (interactive "r\nP")
4037  (if n
4038      (comment-region beg end (prefix-numeric-value n))
4039    (save-excursion
4040      (goto-char beg)
4041      (beginning-of-line)
4042      ;; skip blank lines
4043      (skip-chars-forward " \t\n")
4044      (if (looking-at (concat "[ \t]*\\(" comment-start "+\\)"))
4045	  (if (fboundp 'uncomment-region)
4046	      (uncomment-region beg end)
4047	    (comment-region beg end
4048			    (- (length (buffer-substring
4049					(match-beginning 1)
4050					(match-end 1))))))
4051	(comment-region beg end)))))
4052
4053
4054;; ----------------------------------------------------------------------------
4055;; ----------------------------------------------------------------------------
4056;; ----------------------------------------------------------------------------
4057;; ----------------------------------------------------------------------------
4058;;
4059;; Completion and Routine Info
4060;;
4061
4062;; String "intern" functions
4063
4064;; For the completion and routine info function, we want to normalize
4065;; the case of procedure names etc.  We do this by "interning" these
4066;; string is a hand-crafted way.  Hashes are used to map the downcase
4067;; version of the strings to the cased versions.  Most *-sint-*
4068;; variables consist of *two* hashes, a buffer+shell, followed by a
4069;; system hash.  The former is re-scanned, and the latter takes case
4070;; precedence.
4071;;
4072;; Since these cased versions are really lisp objects, we can use `eq'
4073;; to search, which is a large performance boost.  All new strings
4074;; need to be "sinterned".  We do this as early as possible after
4075;; getting these strings from completion or buffer substrings.  So
4076;; most of the code can simply assume to deal with "sinterned"
4077;; strings.  The only exception is that the functions which scan whole
4078;; buffers for routine information do not intern the grabbed strings.
4079;; This is only done afterwards.  Therefore in these functions it is
4080;; *not* safe to assume the strings can be compared with `eq' and be
4081;; fed into the routine assq functions.
4082
4083;; Here we define the hashing functions.
4084
4085;; The variables which hold the hashes.
4086(defvar idlwave-sint-routines '(nil))
4087(defvar idlwave-sint-keywords '(nil))
4088(defvar idlwave-sint-methods  '(nil))
4089(defvar idlwave-sint-classes  '(nil))
4090(defvar idlwave-sint-dirs    '(nil))
4091(defvar idlwave-sint-libnames '(nil))
4092
4093(defun idlwave-reset-sintern (&optional what)
4094  "Reset all sintern hashes."
4095  ;; Make sure the hash functions are accessible.
4096  (unless (and (fboundp 'gethash)
4097               (fboundp 'puthash))
4098    (require 'cl)
4099    (or (fboundp 'puthash)
4100        (defalias 'puthash 'cl-puthash)))
4101  (let ((entries '((idlwave-sint-routines 1000 10)
4102		   (idlwave-sint-keywords 1000 10)
4103		   (idlwave-sint-methods   100 10)
4104		   (idlwave-sint-classes    10 10))))
4105
4106    ;; Make sure these are lists
4107    (cl-loop for entry in entries
4108      for var = (car entry)
4109      do (if (not (consp (symbol-value var))) (set var (list nil))))
4110
4111    ;; Reset the system & library hash
4112    (when (or (eq what t) (eq what 'syslib)
4113	      (null (cdr idlwave-sint-routines)))
4114      (cl-loop for entry in entries
4115	for var = (car entry) for size = (nth 1 entry)
4116	do (setcdr (symbol-value var)
4117		   (make-hash-table ':size size ':test 'equal)))
4118      (setq idlwave-sint-dirs nil
4119	    idlwave-sint-libnames nil))
4120
4121    ;; Reset the buffer & shell hash
4122    (when (or (eq what t) (eq what 'bufsh)
4123	      (null (car idlwave-sint-routines)))
4124      (cl-loop for entry in entries
4125	for var = (car entry) for size = (nth 1 entry)
4126	do (setcar (symbol-value var)
4127		   (make-hash-table ':size size ':test 'equal))))))
4128
4129(defun idlwave-sintern-routine-or-method (name &optional class set)
4130  (if class
4131      (idlwave-sintern-method name set)
4132    (idlwave-sintern-routine name set)))
4133
4134(defun idlwave-sintern (stype &rest args)
4135  (apply (intern (concat "idlwave-sintern-" (symbol-name stype))) args))
4136
4137;;(defmacro idlwave-sintern (type var)
4138;;  `(cond ((not (stringp name)) name)
4139;;	 ((gethash (downcase name) (cdr ,var)))
4140;;	 ((gethash (downcase name) (car ,var)))
4141;;	 (set (idlwave-sintern-set name ,type ,var set))
4142;;	 (name)))
4143
4144(defun idlwave-sintern-routine (name &optional set)
4145  (cond ((not (stringp name)) name)
4146	((gethash (downcase name) (cdr idlwave-sint-routines)))
4147	((gethash (downcase name) (car idlwave-sint-routines)))
4148	(set (idlwave-sintern-set name 'routine idlwave-sint-routines set))
4149	(name)))
4150(defun idlwave-sintern-keyword (name &optional set)
4151  (cond ((not (stringp name)) name)
4152	((gethash (downcase name) (cdr idlwave-sint-keywords)))
4153	((gethash (downcase name) (car idlwave-sint-keywords)))
4154	(set (idlwave-sintern-set name 'keyword idlwave-sint-keywords set))
4155	(name)))
4156(defun idlwave-sintern-method (name &optional set)
4157  (cond ((not (stringp name)) name)
4158	((gethash (downcase name) (cdr idlwave-sint-methods)))
4159	((gethash (downcase name) (car idlwave-sint-methods)))
4160	(set (idlwave-sintern-set name 'method idlwave-sint-methods set))
4161	(name)))
4162(defun idlwave-sintern-class (name &optional set)
4163  (cond ((not (stringp name)) name)
4164	((gethash (downcase name) (cdr idlwave-sint-classes)))
4165	((gethash (downcase name) (car idlwave-sint-classes)))
4166	(set (idlwave-sintern-set name 'class idlwave-sint-classes set))
4167	(name)))
4168
4169(defun idlwave-sintern-dir (dir &optional set)
4170  (car (or (member dir idlwave-sint-dirs)
4171	   (setq idlwave-sint-dirs (cons dir idlwave-sint-dirs)))))
4172(defun idlwave-sintern-libname (name &optional set)
4173  (car (or (member name idlwave-sint-libnames)
4174	   (setq idlwave-sint-libnames (cons name idlwave-sint-libnames)))))
4175
4176(defun idlwave-sintern-set (name type tables set)
4177  (let* ((func (or (cdr (assq type idlwave-completion-case))
4178		   'identity))
4179	 (iname (funcall (if (eq func 'preserve) 'identity func) name))
4180	 (table (if (eq set 'sys) (cdr tables) (car tables))))
4181    (puthash (downcase name) iname table)
4182    iname))
4183
4184(defun idlwave-sintern-keyword-list (kwd-list &optional set)
4185  "Sintern a set of keywords (file (key . link) (key2 . link2) ...)"
4186  (mapc (lambda(x)
4187	  (setcar x (idlwave-sintern-keyword (car x) set)))
4188	(cdr kwd-list))
4189  kwd-list)
4190
4191(defun idlwave-sintern-rinfo-list (list &optional set default-dir)
4192  "Sintern all strings in the rinfo LIST.
4193With optional parameter SET: also set new patterns.  Probably this
4194will always have to be t.  If DEFAULT-DIR is passed, it is used as
4195the base of the directory."
4196  (let (entry name type class kwds res source call new)
4197    (while list
4198      (setq entry (car list)
4199	    list (cdr list)
4200	    name (car entry)
4201	    type (nth 1 entry)
4202	    class (nth 2 entry)
4203	    source (nth 3 entry)
4204	    call (nth 4 entry)
4205	    kwds (nthcdr 5 entry))
4206
4207      ;; The class and name
4208      (if class
4209	  (progn
4210	    (if (symbolp class) (setq class (symbol-name class)))
4211	    (setq class (idlwave-sintern-class class set))
4212	    (setq name (idlwave-sintern-method name set)))
4213	(setq name (idlwave-sintern-routine name set)))
4214
4215      ;; The source
4216      (let ((source-type (car source))
4217	    (source-file  (nth 1 source))
4218	    (source-dir  (if default-dir
4219			     (file-name-as-directory default-dir)
4220			   (nth 2 source)))
4221	    (source-lib (nth 3 source)))
4222	(if (stringp source-dir)
4223	    (setq source-dir (idlwave-sintern-dir source-dir set)))
4224	(if (stringp source-lib)
4225	    (setq source-lib (idlwave-sintern-libname source-lib set)))
4226	(setq source (list source-type source-file source-dir source-lib)))
4227
4228      ;; The keywords
4229      (setq kwds (mapcar (lambda (x)
4230			   (idlwave-sintern-keyword-list x set))
4231			 kwds))
4232
4233      ;; Build a canonicalized list
4234      (setq new (nconc (list name type class source call) kwds)
4235	    res (cons new res)))
4236    (nreverse res)))
4237
4238;; Creating new sintern tables
4239
4240(defun idlwave-new-sintern-type (tag)
4241  "Define a variable and a function to sintern the new type TAG.
4242This defines the function `idlwave-sintern-TAG' and the variable
4243`idlwave-sint-TAGs'."
4244  (let* ((name (symbol-name tag))
4245	 (names (concat name "s"))
4246	 (var (intern (concat "idlwave-sint-" names)))
4247	 (func (intern (concat "idlwave-sintern-" name))))
4248    (set var nil) ; initial value of the association list
4249    (fset func    ; set the function
4250	  `(lambda (name &optional set)
4251	     (cond ((not (stringp name)) name)
4252		   ((cdr (assoc (downcase name) ,var)))
4253		   (set
4254		    (setq ,var (cons (cons (downcase name) name) ,var))
4255		    name)
4256		   (name))))))
4257
4258(defun idlwave-reset-sintern-type (tag)
4259  "Reset the sintern variable associated with TAG."
4260  (set (intern (concat "idlwave-sint-" (symbol-name tag) "s")) nil))
4261
4262;;---------------------------------------------------------------------------
4263
4264
4265;; The variables which hold the information
4266(defvar idlwave-system-routines nil
4267  "Holds the routine-info obtained by scanning buffers.")
4268(defvar idlwave-buffer-routines nil
4269  "Holds the routine-info obtained by scanning buffers.")
4270(defvar idlwave-compiled-routines nil
4271  "Holds the routine-info obtained by asking the shell.")
4272(defvar idlwave-unresolved-routines nil
4273  "Holds the unresolved routine-info obtained by asking the shell.")
4274(defvar idlwave-user-catalog-routines nil
4275  "Holds the procedure routine-info from the user scan.")
4276(defvar idlwave-library-catalog-routines nil
4277  "Holds the procedure routine-info from the .idlwave_catalog library files.")
4278(defvar idlwave-library-catalog-libname nil
4279  "Name of library catalog loaded from .idlwave_catalog files.")
4280(defvar idlwave-path-alist nil
4281  "Alist with !PATH directories and zero or more flags if the dir has
4282been scanned in a user catalog ('user) or discovered in a library
4283catalog \('lib).")
4284(defvar idlwave-true-path-alist nil
4285  "Like `idlwave-path-alist', but with true filenames.")
4286(defvar idlwave-routines nil
4287  "Holds the combined procedure/function/method routine-info.")
4288(defvar idlwave-class-alist nil
4289  "Holds the class names known to IDLWAVE.")
4290(defvar idlwave-class-history nil
4291  "The history of classes selected with the minibuffer.")
4292(defvar idlwave-force-class-query nil)
4293(defvar idlwave-before-completion-wconf nil
4294  "The window configuration just before the completion buffer was displayed.")
4295(defvar idlwave-last-system-routine-info-cons-cell nil
4296  "The last cons cell in the system routine info.")
4297
4298;;
4299;; The code to get routine info from different sources.
4300
4301(defvar idlwave-system-routines)
4302(defvar idlwave-catalog-process nil
4303  "The background process currently updating the catalog.")
4304
4305(defun idlwave-routines ()
4306  "Provide a list of IDL routines.
4307This routine loads the builtin routines on the first call.
4308Later it only returns the value of the variable."
4309  (if (and idlwave-catalog-process
4310	   (processp idlwave-catalog-process))
4311      (progn
4312	(cond
4313	 ((equal (process-status idlwave-catalog-process) 'exit)
4314	  (message "updating........")
4315	  (setq idlwave-catalog-process nil)
4316	  (idlwave-update-routine-info '(4)))
4317	 ((equal (process-status idlwave-catalog-process) 'run)
4318	  ;; Keep it running...
4319	  )
4320	 (t
4321	  ;; Something is wrong, get rid of the process
4322	  (message "Problem with catalog process") (beep)
4323	  (condition-case nil
4324	      (kill-process idlwave-catalog-process)
4325	    (error nil))
4326	  (setq idlwave-catalog-process nil)))))
4327  (or idlwave-routines
4328      (progn
4329	(idlwave-update-routine-info)
4330	;; return the current value
4331	idlwave-routines)))
4332
4333(defvar idlwave-update-rinfo-hook nil
4334  "List of functions which should run after a global rinfo update.
4335Does not run after automatic updates of buffer or the shell.")
4336
4337(defun idlwave-rescan-catalog-directories ()
4338  "Rescan the previously selected directories.  For batch processing."
4339  (idlwave-update-routine-info '(16)))
4340
4341(defun idlwave-rescan-asynchronously ()
4342  "Dispatch another Emacs instance to update the idlwave catalog.
4343After the process finishes normally, the first access to routine info
4344will re-read the catalog."
4345  (interactive)
4346  (if (processp idlwave-catalog-process)
4347      (if (eq (process-status idlwave-catalog-process) 'run)
4348	  (if (yes-or-no-p "A catalog-updating process is running.  Kill it? ")
4349	      (progn
4350		(condition-case nil
4351		    (kill-process idlwave-catalog-process)
4352		  (error nil))
4353		(error "Process killed, no new process started"))
4354	    (error "Quit"))
4355	(condition-case nil
4356	    (kill-process idlwave-catalog-process)
4357	  (error nil))))
4358  (if (or (not idlwave-user-catalog-file)
4359	  (not (stringp idlwave-user-catalog-file))
4360	  (not (file-regular-p idlwave-user-catalog-file)))
4361      (error "No catalog has been produced yet"))
4362  (let* ((emacs (concat invocation-directory invocation-name))
4363	 (args (list "-batch"
4364		     "-l" (expand-file-name "~/.emacs")
4365		     "-l" "idlwave"
4366		     "-f" "idlwave-rescan-catalog-directories"))
4367	 (process (apply 'start-process "idlcat"
4368			 nil emacs args)))
4369    (setq idlwave-catalog-process process)
4370    (set-process-sentinel
4371     process
4372     (lambda (pro why)
4373       (when (string-match "finished" why)
4374	 (setq idlwave-routines nil
4375	       idlwave-system-routines nil
4376	       idlwave-catalog-process nil)
4377	 (or (idlwave-start-load-rinfo-timer)
4378	     (idlwave-update-routine-info '(4))))))
4379    (message "Background job started to update catalog file")))
4380
4381
4382;; Format for all routine info user catalog, library catalogs, etc.:
4383;;
4384;; ("ROUTINE" type class
4385;;  (system) | (lib pro_file dir "LIBNAME") | (user pro_file dir "USERLIB") |
4386;;  (buffer pro_file dir) | (compiled pro_file dir)
4387;;   "calling_string" ("HELPFILE" (("KWD1" . link1) ...))
4388;;                    ("HELPFILE2" (("KWD2" . link) ...)) ...)
4389;;
4390;; DIR will be supplied dynamically while loading library catalogs,
4391;; and is sinterned to save space, as is LIBNAME.  PRO_FILE can be a
4392;; complete filepath, in which case DIR is unnecessary.  HELPFILE can
4393;; be nil, as can LINK1, etc., if no HTML help is available.
4394
4395
4396(defvar idlwave-load-rinfo-idle-timer)
4397(defvar idlwave-shell-path-query)
4398
4399(defun idlwave-update-routine-info (&optional arg no-concatenate)
4400  "Update the internal routine-info lists.
4401These lists are used by `idlwave-routine-info' (\\[idlwave-routine-info])
4402and by `idlwave-complete' (\\[idlwave-complete]) to provide information
4403about individual routines.
4404
4405The information can come from 4 sources:
44061. IDL programs in the current editing session
44072. Compiled modules in an IDL shell running as Emacs subprocess
44083. A list which covers the IDL system routines.
44094. A list which covers the prescanned library files.
4410
4411Scans all IDLWAVE-mode buffers of the current editing session (see
4412`idlwave-scan-all-buffers-for-routine-info').
4413When an IDL shell is running, this command also queries the IDL program
4414for currently compiled routines.
4415
4416With prefix ARG, also reload the system and library lists.
4417With two prefix ARG's, also rescans the chosen user catalog tree.
4418With three prefix args, dispatch asynchronous process to do the update.
4419
4420If NO-CONCATENATE is non-nil, don't pre-concatenate the routine info
4421lists, but instead wait for the shell query to complete and
4422asynchronously finish updating routine info.  This is set
4423automatically when called interactively.  When you need routine
4424information updated immediately, leave NO-CONCATENATE nil."
4425  (interactive "P\np")
4426  ;; Stop any idle processing
4427  (if (or (and (fboundp 'itimerp)
4428	       (itimerp idlwave-load-rinfo-idle-timer))
4429	  (and (fboundp 'timerp)
4430	       (timerp idlwave-load-rinfo-idle-timer)))
4431      (cancel-timer idlwave-load-rinfo-idle-timer))
4432  (cond
4433   ((equal arg '(64))
4434    ;; Start a background process which updates the catalog.
4435    (idlwave-rescan-asynchronously))
4436   ((equal arg '(16))
4437    ;; Update the user catalog now, and wait for them.
4438    (idlwave-create-user-catalog-file t))
4439   (t
4440    (let* ((load (or arg
4441		     idlwave-buffer-case-takes-precedence
4442		     (null idlwave-routines)))
4443	   ;; The override-idle means, even if the idle timer has done some
4444	   ;; preparing work, load and renormalize everything anyway.
4445	   (override-idle (or arg idlwave-buffer-case-takes-precedence)))
4446
4447      (setq idlwave-buffer-routines nil
4448	    idlwave-compiled-routines nil
4449	    idlwave-unresolved-routines nil)
4450      ;; Reset the appropriate hashes
4451      (if (get 'idlwave-reset-sintern 'done-by-idle)
4452	  ;; reset was already done in idle time, so skip this step now once
4453	  (put 'idlwave-reset-sintern 'done-by-idle nil)
4454	(idlwave-reset-sintern (cond (load t)
4455				     ((null idlwave-system-routines) t)
4456				     (t 'bufsh))))
4457
4458      (if idlwave-buffer-case-takes-precedence
4459	  ;; We can safely scan the buffer stuff first
4460	  (progn
4461	    (idlwave-update-buffer-routine-info)
4462	    (and load (idlwave-load-all-rinfo override-idle)))
4463	;; We first do the system info, and then the buffers
4464	(and load (idlwave-load-all-rinfo override-idle))
4465	(idlwave-update-buffer-routine-info))
4466
4467      ;; Let's see if there is a shell
4468      (let* ((shell-is-running (and (fboundp 'idlwave-shell-is-running)
4469				    (idlwave-shell-is-running)))
4470	     (ask-shell (and shell-is-running
4471			     idlwave-query-shell-for-routine-info)))
4472
4473	;; Load the library catalogs again, first re-scanning the path
4474	(when arg
4475	  (if shell-is-running
4476	      (idlwave-shell-send-command idlwave-shell-path-query
4477					  '(progn
4478					     (idlwave-shell-get-path-info)
4479					     (idlwave-scan-library-catalogs))
4480					  'hide)
4481	    (idlwave-scan-library-catalogs)))
4482
4483	(if (or (not ask-shell)
4484		(not no-concatenate))
4485	    ;; 1. If we are not going to ask the shell, we need to do the
4486	    ;;    concatenation now.
4487	    ;; 2. When this function is called non-interactively, it
4488	    ;;    means that someone needs routine info *now*.  The
4489	    ;;    shell update causes the concatenation to be
4490	    ;;    *delayed*, so not in time for the current command.
4491	    ;;    Therefore, we do a concatenation now, even though
4492	    ;;    the shell might do it again.
4493	    (idlwave-concatenate-rinfo-lists nil 'run-hooks))
4494
4495	(when ask-shell
4496	  ;; Ask the shell about the routines it knows of.
4497	  (message "Querying the shell")
4498	  (idlwave-shell-update-routine-info nil t)))))))
4499
4500
4501(defvar idlwave-load-rinfo-steps-done (make-vector 6 nil))
4502(defvar idlwave-load-rinfo-idle-timer nil)
4503(defun idlwave-start-load-rinfo-timer ()
4504  (if (or (and (fboundp 'itimerp)
4505	       (itimerp idlwave-load-rinfo-idle-timer))
4506	  (and (fboundp 'timerp)
4507	       (timerp idlwave-load-rinfo-idle-timer)))
4508      (cancel-timer idlwave-load-rinfo-idle-timer))
4509  (setq idlwave-load-rinfo-steps-done (make-vector 6 nil))
4510  (setq idlwave-load-rinfo-idle-timer nil)
4511  (if (and idlwave-init-rinfo-when-idle-after
4512	   (numberp idlwave-init-rinfo-when-idle-after)
4513	   (not (equal 0 idlwave-init-rinfo-when-idle-after))
4514	   (not idlwave-routines))
4515      (condition-case nil
4516	  (progn
4517	    (setq idlwave-load-rinfo-idle-timer
4518		  (run-with-idle-timer
4519		   idlwave-init-rinfo-when-idle-after
4520		   nil 'idlwave-load-rinfo-next-step)))
4521	(error nil))))
4522
4523;;------ XML Help routine info system
4524(defun idlwave-load-system-routine-info ()
4525  ;; Load the system routine info from the cached routine info file,
4526  ;; which, if necessary, will be re-created from the XML file on
4527  ;; disk.  As a last fallback, load the (likely outdated) idlw-rinfo
4528  ;; file distributed with older IDLWAVE versions (<6.0)
4529  (unless (and (load idlwave-xml-system-rinfo-converted-file
4530		     'noerror 'nomessage)
4531	       (idlwave-xml-system-routine-info-up-to-date))
4532    ;; See if we can create it from XML source
4533    (condition-case nil
4534	(idlwave-convert-xml-system-routine-info)
4535      (error
4536       (unless (load idlwave-xml-system-rinfo-converted-file
4537		     'noerror 'nomessage)
4538	 (if idlwave-system-routines
4539	     (message
4540	      "Failed to load converted routine info, using old conversion.")
4541	   (message
4542	    "Failed to convert XML routine info, falling back on idlw-rinfo.")
4543	   (if (not (load "idlw-rinfo" 'noerror 'nomessage))
4544	       (message
4545		"Could not locate any system routine information."))))))))
4546
4547(defun idlwave-xml-system-routine-info-up-to-date()
4548  (let* ((dir (file-name-as-directory
4549	       (expand-file-name "help/online_help" (idlwave-sys-dir))))
4550	 (catalog-file (expand-file-name "idl_catalog.xml" dir)))
4551    (file-newer-than-file-p ;converted file is newer than catalog
4552     idlwave-xml-system-rinfo-converted-file
4553     catalog-file)))
4554
4555(defvar idlwave-system-class-info nil) ; Gathered from idlw-rinfo
4556(defvar idlwave-system-variables-alist nil
4557  "Alist of system variables and the associated structure tags.
4558Gets set in cached XML rinfo, or `idlw-rinfo.el'.")
4559(defvar idlwave-executive-commands-alist nil
4560  "Alist of system variables and their help files.")
4561(defvar idlwave-help-special-topic-words nil)
4562
4563
4564(defun idlwave-shorten-syntax (syntax name &optional class)
4565  ;; From a list of syntax statements, shorten with %s and group with "or"
4566  (let ((case-fold-search t))
4567    (mapconcat
4568     (lambda (x)
4569       (while (string-match name x)
4570	 (setq x (replace-match "%s" t t x)))
4571       (if class
4572	   (while (string-match class x)
4573	     (setq x (replace-match "%s" t t x))))
4574       x)
4575     (nreverse syntax)
4576     " or ")))
4577
4578(defun idlwave-xml-create-class-method-lists (xml-entry)
4579  ;; Create a class list entry from the xml parsed list., returning a
4580  ;; cons of form (class-entry method-entries).
4581  (let* ((nameblock (nth 1 xml-entry))
4582	 (class (cdr (assq 'name nameblock)))
4583	 (link (cdr (assq 'link nameblock)))
4584	 (params (cddr xml-entry))
4585	 (case-fold-search t)
4586	 class-entry
4587	 method methods-entry extra-kwds
4588	 props get-props set-props init-props inherits
4589	 pelem ptype)
4590    (while params
4591      (setq pelem (car params))
4592      (when (listp pelem)
4593	(setq ptype (car pelem)
4594	      props (car (cdr pelem)))
4595	(cond
4596	 ((eq ptype 'SUPERCLASS)
4597	  (let ((pname (cdr (assq 'name props)))
4598		(plink (cdr (assq 'link props))))
4599	    (unless (and (string= pname "None")
4600			 (string= plink "None"))
4601	      (push pname inherits))))
4602
4603	 ((eq ptype 'PROPERTY)
4604	  (let ((pname (cdr (assq 'name props)))
4605		(plink (cdr (assq 'link props)))
4606		(get (string= (cdr (assq 'get props)) "Yes"))
4607		(set (string= (cdr (assq 'set props)) "Yes"))
4608		(init (string= (cdr (assq 'init props)) "Yes")))
4609	    (if get (push (list pname plink) get-props))
4610	    (if set (push (list pname plink) set-props))
4611	    (if init (push (list pname plink) init-props))))
4612
4613	 ((eq ptype 'METHOD)
4614	  (setq method (cdr (assq 'name props)))
4615	  (setq extra-kwds ;;Assume all property keywords are gathered already
4616		(cond
4617		 ((string-match (concat class "::Init") method)
4618		  (put 'init-props 'matched t)
4619		  init-props)
4620		 ((string-match (concat class "::GetProperty") method)
4621		  (put 'get-props 'matched t)
4622		  get-props)
4623		 ((string-match (concat class "::SetProperty") method)
4624		  (put 'set-props 'matched t)
4625		  set-props)
4626		 (t nil)))
4627	  (setq methods-entry
4628		(nconc (idlwave-xml-create-rinfo-list pelem class extra-kwds)
4629		       methods-entry)))
4630	 (t)))
4631      (setq params (cdr params)))
4632    ;;(unless (get 'init-props 'matched)
4633    ;;  (message "Failed to match Init in class %s" class))
4634    ;;(unless (get 'get-props 'matched)
4635    ;;  (message "Failed to match GetProperty in class %s" class))
4636    ;;(unless (get 'set-props 'matched)
4637    ;;  (message "Failed to match SetProperty in class %s" class))
4638    (setq class-entry
4639	  (if inherits
4640	      (list class (append '(inherits) inherits) (list 'link link))
4641	    (list class (list 'link link))))
4642    (cons class-entry methods-entry)))
4643
4644(defun idlwave-xml-create-rinfo-list (xml-entry &optional class extra-kws)
4645  ;; Create correctly structured list elements from ROUTINE or METHOD
4646  ;; XML list structures.  Return a list of list elements, with more
4647  ;; than one sub-list possible if a routine can serve as both
4648  ;; procedure and function (e.g. call_method).
4649  (let* ((nameblock (nth 1 xml-entry))
4650	 (name (cdr (assq 'name nameblock)))
4651	 (link (cdr (assq 'link nameblock)))
4652	 (params (cddr xml-entry))
4653	 (syntax-vec (make-vector 3 nil)) ; procedure, function, exec command
4654	 (case-fold-search t)
4655	 syntax kwd klink pref-list kwds pelem ptype props result type)
4656    (if class ;; strip out class name from class method name string
4657	(if (string-match (concat class "::") name)
4658	    (setq name (substring name (match-end 0)))))
4659    (while params
4660      (setq pelem (car params))
4661      (when (listp pelem)
4662	(setq ptype (car pelem)
4663	      props (car (cdr pelem)))
4664	(cond
4665	 ((eq ptype 'SYNTAX)
4666	  (setq syntax (cdr (assq 'name props)))
4667	  (if (string-match "-&gt;" syntax)
4668	      (setq syntax (replace-match "->" t nil syntax)))
4669	  (setq type (cdr (assq 'type props)))
4670	  (push syntax
4671		(aref syntax-vec (cond
4672				  ((string-match "^pro" type) 0)
4673				  ((string-match "^fun" type) 1)
4674				  ((string-match "^exec" type) 2)))))
4675	 ((eq ptype 'KEYWORD)
4676	  (setq kwd (cdr (assq 'name props))
4677		klink (cdr (assq 'link props)))
4678	  (if (string-match "^\\[XY\\(Z?\\)\\]" kwd)
4679	      (progn
4680		(setq pref-list
4681		      (if (match-string 1 kwd) '("X" "Y" "Z") '("X" "Y"))
4682		      kwd (substring kwd (match-end 0)))
4683		(cl-loop for x in pref-list do
4684		      (push (list (concat x kwd) klink) kwds)))
4685	    (push (list kwd klink) kwds)))
4686
4687	 (t))); Do nothing for the others
4688      (setq params (cdr params)))
4689
4690    ;; Debug
4691    ;; (if (and (null (aref syntax-vec 0))
4692    ;;          (null (aref syntax-vec 1))
4693    ;;          (null (aref syntax-vec 2)))
4694    ;;   (with-current-buffer (get-buffer-create "IDL_XML_catalog_complaints")
4695    ;;     (if class
4696    ;;         (insert (format "Missing SYNTAX entry for %s::%s\n" class name))
4697    ;;       (insert (message "Missing SYNTAX entry for %s\n" name)))))
4698
4699    ;; Executive commands are treated specially
4700    (if (aref syntax-vec 2)
4701	(cons (substring name 1) link)
4702      (if extra-kws (setq kwds (nconc kwds extra-kws)))
4703      (setq kwds (idlwave-rinfo-group-keywords kwds link))
4704      (cl-loop for idx from 0 to 1 do
4705	    (if (aref syntax-vec idx)
4706		(push (append (list name (if (eq idx 0) 'pro 'fun)
4707				    class '(system)
4708				    (idlwave-shorten-syntax
4709				     (aref syntax-vec idx) name class))
4710			      kwds) result)))
4711      result)))
4712
4713
4714(defun idlwave-rinfo-group-keywords (kwds master-link)
4715  ;; Group keywords by link file, as a list with elements
4716  ;; (linkfile ( ("KWD1" . link1) ("KWD2" . link2))
4717  (let (kwd link anchor linkfiles block master-elt)
4718    (while kwds
4719      (setq kwd (car kwds)
4720	    link (idlwave-split-link-target (nth 1 kwd))
4721	    anchor (cdr link)
4722	    link (car link)
4723	    kwd (car kwd))
4724      (if (setq block (assoc link linkfiles))
4725	  (push (cons kwd anchor) (cdr block))
4726	(push (list link (cons kwd anchor)) linkfiles))
4727      (setq kwds (cdr kwds)))
4728    ;; Ensure the master link is there
4729    (if (setq master-elt (assoc master-link linkfiles))
4730	(if (eq (car linkfiles) master-elt)
4731	    linkfiles
4732 	  (cons master-elt (delq master-elt linkfiles)))
4733      (push (list master-link) linkfiles))))
4734
4735(defun idlwave-convert-xml-clean-statement-aliases (aliases)
4736  ;; Clean up the syntax of routines which are actually aliases by
4737  ;; removing the "OR" from the statements
4738  (let (syntax entry)
4739    (cl-loop for x in aliases do
4740	  (setq entry (assoc x idlwave-system-routines))
4741	  (when entry
4742	    (while (string-match " +or +" (setq syntax (nth 4 entry)))
4743	      (setf (nth 4 entry) (replace-match ", " t t syntax)))))))
4744
4745(defun idlwave-convert-xml-clean-routine-aliases (aliases)
4746  ;; Duplicate and trim original routine aliases from rinfo list
4747  ;; This if for, e.g. OPENR/OPENW/OPENU
4748  (let (alias remove-list new parts all-parts)
4749    (cl-loop for x in aliases do
4750	  (when (setq parts (split-string (cdr x) "/"))
4751	    (setq new (assoc (cdr x) all-parts))
4752	    (unless new
4753	      (setq new (cons (cdr x) parts))
4754	      (push new all-parts))
4755	    (setcdr new (delete (car x) (cdr new)))))
4756
4757    ;; Add any missing aliases (separate by slashes)
4758    (cl-loop for x in all-parts do
4759	  (if (cdr x)
4760	      (push (cons (nth 1 x) (car x)) aliases)))
4761
4762    (cl-loop for x in aliases do
4763	  (when (setq alias (assoc (cdr x) idlwave-system-routines))
4764	    (unless (memq alias remove-list) (push alias remove-list))
4765	    (setq alias (copy-sequence alias))
4766	    (setcar alias (car x))
4767	    (push alias idlwave-system-routines)))
4768    (cl-loop for x in remove-list do
4769	  (delq x idlwave-system-routines))))
4770
4771(defun idlwave-convert-xml-clean-sysvar-aliases (aliases)
4772  ;; Duplicate and trim original routine aliases from rinfo list
4773  ;; This if for, e.g. !X, !Y, !Z.
4774  (let (alias remove-list)
4775    (cl-loop for x in aliases do
4776	  (when (setq alias (assoc (cdr x) idlwave-system-variables-alist))
4777	    (unless (memq alias remove-list) (push alias remove-list))
4778	    (setq alias (copy-sequence alias))
4779	    (setcar alias (car x))
4780	    (push alias idlwave-system-variables-alist)))
4781    (cl-loop for x in remove-list do
4782	  (delq x idlwave-system-variables-alist))))
4783
4784
4785(defun idlwave-xml-create-sysvar-alist (xml-entry)
4786  ;; Create a sysvar list entry from the xml parsed list.
4787  (let* ((nameblock (nth 1 xml-entry))
4788	 (name (cdr (assq 'name nameblock)))
4789	 (sysvar (substring name (progn (string-match "^ *!" name)
4790					(match-end 0))))
4791	 (link (cdr (assq 'link nameblock)))
4792	 (params (cddr xml-entry))
4793	 (case-fold-search t)
4794	 pelem ptype props tags)
4795    (while params
4796      (setq pelem (car params))
4797      (when (listp pelem)
4798	(setq ptype (car pelem)
4799	      props (car (cdr pelem)))
4800	(cond
4801	 ((eq ptype 'FIELD)
4802	  (push (cons (cdr (assq 'name props))
4803		      (cdr
4804		       (idlwave-split-link-target (cdr (assq 'link props)))))
4805		tags))))
4806	(setq params (cdr params)))
4807    (delq nil
4808	  (list sysvar (if tags (cons 'tags tags)) (list 'link link)))))
4809
4810
4811(defvar idlwave-xml-routine-info-file nil)
4812
4813(defun idlwave-save-routine-info ()
4814  (if idlwave-xml-routine-info-file
4815      (with-temp-file idlwave-xml-system-rinfo-converted-file
4816	(insert
4817	 (concat ";; *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
4818;; IDLWAVE Routine Information File (IDLWAVE version " idlwave-mode-version ")
4819;; Automatically generated from source file:
4820;;  " idlwave-xml-routine-info-file "
4821;; on " (current-time-string) "
4822;; Do not edit."))
4823	(insert (format "\n(setq idlwave-xml-routine-info-file \n    \"%s\")"
4824			idlwave-xml-routine-info-file))
4825	(insert "\n(setq idlwave-system-routines\n    '")
4826	(prin1 idlwave-system-routines (current-buffer))
4827	(insert ")")
4828	(insert "\n(setq idlwave-system-variables-alist\n    '")
4829	(prin1 idlwave-system-variables-alist (current-buffer))
4830	(insert ")")
4831	(insert "\n(setq idlwave-system-class-info\n    '")
4832	(prin1 idlwave-system-class-info (current-buffer))
4833	(insert ")")
4834	(insert "\n(setq idlwave-executive-commands-alist\n    '")
4835	(prin1 idlwave-executive-commands-alist (current-buffer))
4836	(insert ")")
4837	(insert "\n(setq idlwave-help-special-topic-words\n    '")
4838	(prin1 idlwave-help-special-topic-words (current-buffer))
4839	(insert ")"))))
4840
4841(defun idlwave-convert-xml-system-routine-info ()
4842  "Convert XML supplied IDL routine info into internal form.
4843Cache to disk for quick recovery."
4844  (interactive)
4845  (let* ((dir (file-name-as-directory
4846	       (expand-file-name "help/online_help" (idlwave-sys-dir))))
4847	 (catalog-file (expand-file-name "idl_catalog.xml" dir))
4848	 (elem-cnt 0)
4849	 props rinfo msg-cnt elem type nelem class-result alias
4850	 routines routine-aliases statement-aliases sysvar-aliases)
4851    (if (not (file-exists-p catalog-file))
4852	(error "No such XML routine info file: %s" catalog-file)
4853      (if (not (file-readable-p catalog-file))
4854	  (error "Cannot read XML routine info file: %s" catalog-file)))
4855    (message "Reading XML routine info...")
4856    (setq rinfo (xml-parse-file catalog-file))
4857    (message "Reading XML routine info...done")
4858    (setq rinfo (assq 'CATALOG rinfo))
4859    (unless rinfo (error "Failed to parse XML routine info"))
4860    ;;(setq rinfo (car rinfo)) ; Skip the catalog stuff.
4861
4862    (setq rinfo (cddr rinfo))
4863
4864    (setq nelem (length rinfo)
4865	  msg-cnt (/ nelem 20))
4866
4867    (setq idlwave-xml-routine-info-file nil)
4868    (message "Converting XML routine info...")
4869    (setq idlwave-system-routines nil
4870	  idlwave-system-variables-alist nil
4871	  idlwave-system-class-info nil
4872	  idlwave-executive-commands-alist nil
4873	  idlwave-help-special-topic-words nil)
4874
4875    (while rinfo
4876      (setq elem (car rinfo)
4877	    rinfo (cdr rinfo))
4878      (cl-incf elem-cnt)
4879      (when (listp elem)
4880	(setq type (car elem)
4881	      props (car (cdr elem)))
4882	(if (= (mod elem-cnt msg-cnt) 0)
4883	    (message "Converting XML routine info...%2d%%"
4884		     (floor (* elem-cnt 100.0) nelem)))
4885	(cond
4886	 ((eq type 'ROUTINE)
4887	  (if (setq alias (assq 'alias_to props))
4888	      (push (cons (cdr (assq 'name props)) (cdr alias))
4889		    routine-aliases)
4890	    (setq routines (idlwave-xml-create-rinfo-list elem))
4891	    (if (listp (cdr routines))
4892		(setq idlwave-system-routines
4893		      (nconc idlwave-system-routines routines))
4894	      ;; a cons cell is an executive commands
4895	      (push routines idlwave-executive-commands-alist))))
4896
4897	 ((eq type 'CLASS)
4898	  (setq class-result (idlwave-xml-create-class-method-lists elem))
4899	  (push (car class-result) idlwave-system-class-info)
4900	  (setq idlwave-system-routines
4901	  (nconc idlwave-system-routines (cdr class-result))))
4902
4903	 ((eq type 'STATEMENT)
4904	  (push (cons (cdr (assq 'name props))
4905		      (cdr (assq 'link props)))
4906	  idlwave-help-special-topic-words)
4907	  ;; Save the links to those which are statement aliases (not routines)
4908	  (if (setq alias (assq 'alias_to props))
4909	      (unless (member (cdr alias) statement-aliases)
4910		(push (cdr alias) statement-aliases))))
4911
4912	 ((eq type 'SYSVAR)
4913	  (if (setq alias (cdr (assq 'alias_to props)))
4914	      (push (cons (substring (cdr (assq 'name props)) 1)
4915			  (substring alias 1))
4916		    sysvar-aliases)
4917	    (push (idlwave-xml-create-sysvar-alist elem)
4918		  idlwave-system-variables-alist)))
4919	 (t))))
4920    (idlwave-convert-xml-clean-routine-aliases routine-aliases)
4921    (idlwave-convert-xml-clean-statement-aliases statement-aliases)
4922    (idlwave-convert-xml-clean-sysvar-aliases sysvar-aliases)
4923
4924    (setq idlwave-xml-routine-info-file catalog-file)
4925    (idlwave-save-routine-info)
4926    (message "Converting XML routine info...done")))
4927
4928
4929;; ("ROUTINE" type class
4930;;  (system) | (lib pro_file dir "LIBNAME") | (user pro_file dir "USERLIB") |
4931;;  (buffer pro_file dir) | (compiled pro_file dir)
4932;;   "calling_string" ("HELPFILE" (("KWD1" . link1) ...))
4933;;                    ("HELPFILE2" (("KWD2" . link) ...)) ...)
4934
4935
4936(defun idlwave-load-rinfo-next-step ()
4937  (let ((inhibit-quit t)
4938	(arr idlwave-load-rinfo-steps-done))
4939    (if (catch 'exit
4940	  (when (not (aref arr 0))
4941	    (message "Loading system routine info in idle time...")
4942	    (idlwave-load-system-routine-info)
4943	    ;;(load "idlw-rinfo" 'noerror 'nomessage)
4944	    (message "Loading system routine info in idle time...done")
4945	    (aset arr 0 t)
4946	    (throw 'exit t))
4947
4948	  (when (not (aref arr 1))
4949	    (message "Normalizing idlwave-system-routines in idle time...")
4950	    (idlwave-reset-sintern t)
4951	    (put 'idlwave-reset-sintern 'done-by-idle t)
4952	    (setq idlwave-system-routines
4953		  (idlwave-sintern-rinfo-list idlwave-system-routines 'sys))
4954	    (message "Normalizing idlwave-system-routines in idle time...done")
4955	    (aset arr 1 t)
4956	    (throw 'exit t))
4957
4958	  (when (not (aref arr 2))
4959	    (when (and (stringp idlwave-user-catalog-file)
4960		       (file-regular-p idlwave-user-catalog-file))
4961	      (message "Loading user catalog in idle time...")
4962	      (condition-case nil
4963		  (load-file idlwave-user-catalog-file)
4964		(error (throw 'exit nil)))
4965	      ;; Check for the old style catalog and warn
4966	      (if (and
4967		   (boundp 'idlwave-library-routines)
4968		   idlwave-library-routines)
4969		  (progn
4970		    (setq idlwave-library-routines nil)
4971		    (ding)
4972		    (message "Outdated user catalog: %s... recreate"
4973			     idlwave-user-catalog-file))
4974		(message "Loading user catalog in idle time...done")))
4975	    (aset arr 2 t)
4976	    (throw 'exit t))
4977
4978	  (when (not (aref arr 3))
4979	    (when idlwave-user-catalog-routines
4980	      (message "Normalizing user catalog routines in idle time...")
4981	      (setq idlwave-user-catalog-routines
4982		    (idlwave-sintern-rinfo-list
4983		     idlwave-user-catalog-routines 'sys))
4984	      (message
4985	       "Normalizing user catalog routines in idle time...done"))
4986	    (aset arr 3 t)
4987	    (throw 'exit t))
4988
4989	  (when (not (aref arr 4))
4990	    (idlwave-scan-library-catalogs
4991	     "Loading and normalizing library catalogs in idle time...")
4992	    (aset arr 4 t)
4993	    (throw 'exit t))
4994	  (when (not (aref arr 5))
4995	    (message "Finishing initialization in idle time...")
4996	    (idlwave-routines)
4997	    (message "Finishing initialization in idle time...done")
4998	    (aset arr 5 t)
4999	    (throw 'exit nil)))
5000	;; restart the timer
5001	(if (sit-for 1)
5002	    (idlwave-load-rinfo-next-step)
5003	  (setq idlwave-load-rinfo-idle-timer
5004		(run-with-idle-timer
5005		 idlwave-init-rinfo-when-idle-after
5006		 nil 'idlwave-load-rinfo-next-step))))))
5007
5008(defvar idlwave-after-load-rinfo-hook nil)
5009
5010(defun idlwave-load-all-rinfo (&optional force)
5011  ;; Load and case-treat the system, user catalog, and library routine
5012  ;; info files.
5013
5014  ;; System
5015  (when (or force (not (aref idlwave-load-rinfo-steps-done 0)))
5016    ;;(load "idlw-rinfo" 'noerror 'nomessage))
5017    (idlwave-load-system-routine-info))
5018  (when (or force (not (aref idlwave-load-rinfo-steps-done 1)))
5019    (message "Normalizing idlwave-system-routines...")
5020    (setq idlwave-system-routines
5021	  (idlwave-sintern-rinfo-list idlwave-system-routines 'sys))
5022    (message "Normalizing idlwave-system-routines...done"))
5023  (when idlwave-system-routines
5024    (setq idlwave-routines (copy-sequence idlwave-system-routines))
5025    (setq idlwave-last-system-routine-info-cons-cell
5026	  (nthcdr (1- (length idlwave-routines)) idlwave-routines)))
5027
5028  ;; User catalog
5029  (when (and (stringp idlwave-user-catalog-file)
5030	     (file-regular-p idlwave-user-catalog-file))
5031    (condition-case nil
5032	(when (or force (not (aref idlwave-load-rinfo-steps-done 2)))
5033	  (load-file idlwave-user-catalog-file))
5034      (error nil))
5035    (when (and
5036	   (boundp 'idlwave-library-routines)
5037	   idlwave-library-routines)
5038      (setq idlwave-library-routines nil)
5039      (error "Outdated user catalog: %s... recreate"
5040	     idlwave-user-catalog-file))
5041    (setq idlwave-true-path-alist nil)
5042    (when (or force (not (aref idlwave-load-rinfo-steps-done 3)))
5043      (message "Normalizing user catalog routines...")
5044      (setq idlwave-user-catalog-routines
5045	    (idlwave-sintern-rinfo-list
5046	     idlwave-user-catalog-routines 'sys))
5047      (message "Normalizing user catalog routines...done")))
5048
5049  ;; Library catalog
5050  (when (or force (not (aref idlwave-load-rinfo-steps-done 4)))
5051    (idlwave-scan-library-catalogs
5052     "Loading and normalizing library catalogs..."))
5053  (run-hooks 'idlwave-after-load-rinfo-hook))
5054
5055
5056(defun idlwave-update-buffer-routine-info ()
5057  (let (res)
5058    (cond
5059     ((eq idlwave-scan-all-buffers-for-routine-info t)
5060      ;; Scan all buffers, current buffer last
5061      (message "Scanning all buffers...")
5062      (setq res (idlwave-get-routine-info-from-buffers
5063		 (reverse (buffer-list)))))
5064     ((null idlwave-scan-all-buffers-for-routine-info)
5065      ;; Don't scan any buffers
5066      (setq res nil))
5067     (t
5068      ;; Just scan this buffer
5069      (if (derived-mode-p 'idlwave-mode)
5070	  (progn
5071	    (message "Scanning current buffer...")
5072	    (setq res (idlwave-get-routine-info-from-buffers
5073		       (list (current-buffer))))))))
5074    ;; Put the result into the correct variable
5075    (setq idlwave-buffer-routines
5076	  (idlwave-sintern-rinfo-list res 'set))))
5077
5078(defun idlwave-concatenate-rinfo-lists (&optional quiet run-hook)
5079  "Put the different sources for routine information together."
5080  ;; The sequence here is important because earlier definitions shadow
5081  ;; later ones.  We assume that if things in the buffers are newer
5082  ;; then in the shell of the system, they are meant to be different.
5083  (let ((temp (append idlwave-buffer-routines
5084		      idlwave-compiled-routines
5085		      idlwave-library-catalog-routines
5086		      idlwave-user-catalog-routines)))
5087    ;; Not actually used for anything?
5088    (if idlwave-last-system-routine-info-cons-cell
5089	(setcdr idlwave-last-system-routine-info-cons-cell temp)
5090      (setq idlwave-last-system-routine-info-cons-cell (cons temp nil))))
5091  (setq idlwave-class-alist nil)
5092
5093  ;; Give a message with information about the number of routines we have.
5094  (unless quiet
5095    (message
5096     "Routines Found: buffer(%d) compiled(%d) library(%d) user(%d) system(%d)"
5097     (length idlwave-buffer-routines)
5098     (length idlwave-compiled-routines)
5099     (length idlwave-library-catalog-routines)
5100     (length idlwave-user-catalog-routines)
5101     (length idlwave-system-routines)))
5102  (if run-hook
5103      (run-hooks 'idlwave-update-rinfo-hook)))
5104
5105(defun idlwave-class-alist ()
5106  "Return the class alist - make it if necessary."
5107  (or idlwave-class-alist
5108      (let (class)
5109	(cl-loop for x in idlwave-routines do
5110	  (when (and (setq class (nth 2 x))
5111		     (not (assq class idlwave-class-alist)))
5112	    (push (list class) idlwave-class-alist)))
5113	idlwave-class-alist)))
5114
5115;; Three functions for the hooks
5116(defun idlwave-save-buffer-update ()
5117  (idlwave-update-current-buffer-info 'save-buffer))
5118(defun idlwave-kill-buffer-update ()
5119  (idlwave-update-current-buffer-info 'kill-buffer))
5120(defun idlwave-new-buffer-update ()
5121  (idlwave-update-current-buffer-info 'find-file))
5122
5123(defun idlwave-update-current-buffer-info (why)
5124  "Update `idlwave-routines' for current buffer.
5125Can run from `after-save-hook'."
5126  (when (and (derived-mode-p 'idlwave-mode)
5127	     (or (eq t idlwave-auto-routine-info-updates)
5128		 (memq why idlwave-auto-routine-info-updates))
5129	     idlwave-scan-all-buffers-for-routine-info
5130	     idlwave-routines)
5131    (condition-case nil
5132	(let (routines)
5133	  (idlwave-replace-buffer-routine-info
5134	   (buffer-file-name)
5135	   (if (eq why 'kill-buffer)
5136	       nil
5137	     (setq routines
5138		   (idlwave-sintern-rinfo-list
5139		    (idlwave-get-routine-info-from-buffers
5140		     (list (current-buffer))) 'set))))
5141	  (idlwave-concatenate-rinfo-lists 'quiet)
5142	  routines)
5143      (error nil))))
5144
5145(defun idlwave-replace-buffer-routine-info (file new)
5146  "Cut the part from FILE out of `idlwave-buffer-routines' and add NEW."
5147  (let ((list idlwave-buffer-routines)
5148	found)
5149    (while list
5150      ;; The following test uses eq to make sure it works correctly
5151      ;; when two buffers visit the same file.  Then the file names
5152      ;; will be equal, but not eq.
5153      (if (eq (idlwave-routine-source-file (nth 3 (car list))) file)
5154	  (progn
5155	    (setcar list nil)
5156	    (setq found t))
5157	(if found
5158	    ;; End of that section reached. Jump.
5159	    (setq list nil)))
5160      (setq list (cdr list)))
5161    (setq idlwave-buffer-routines
5162	  (append new (delq nil idlwave-buffer-routines)))))
5163
5164;;----- Scanning buffers -------------------
5165
5166(defun idlwave-get-routine-info-from-buffers (buffers)
5167  "Call `idlwave-get-buffer-routine-info' on idlwave-mode buffers in BUFFERS."
5168  (let (buf routine-lists res)
5169    (save-excursion
5170      (while (setq buf (pop buffers))
5171	(set-buffer buf)
5172	(if (and (derived-mode-p 'idlwave-mode)
5173		 buffer-file-name)
5174	    ;; yes, this buffer has the right mode.
5175	    (progn (setq res (condition-case nil
5176				 (idlwave-get-buffer-routine-info)
5177			       (error nil)))
5178		   (push res routine-lists)))))
5179    ;; Concatenate the individual lists and return the result
5180    (apply 'nconc routine-lists)))
5181
5182(defun idlwave-get-buffer-routine-info ()
5183  "Scan the current buffer for routine info.  Return (PRO-LIST FUNC-LIST)."
5184  (let* ((case-fold-search t)
5185	 routine-list string entry)
5186    (save-excursion
5187      (save-restriction
5188	(widen)
5189	(goto-char (point-min))
5190	(while (re-search-forward
5191		"^[ \t]*\\(pro\\|function\\)[ \t]" nil t)
5192	  (setq string (buffer-substring-no-properties
5193			(match-beginning 0)
5194			(progn
5195			  (idlwave-end-of-statement)
5196			  (point))))
5197	  (setq entry (idlwave-parse-definition string))
5198	  (push entry routine-list))))
5199    routine-list))
5200
5201(defvar idlwave-scanning-lib-dir)
5202(defvar idlwave-scanning-lib)
5203(defun idlwave-parse-definition (string)
5204  "Parse a module definition."
5205  (let ((case-fold-search t)
5206	start name args type keywords class)
5207    ;; Remove comments
5208    (while (string-match ";.*" string)
5209      (setq string (replace-match "" t t string)))
5210    ;; Remove the continuation line stuff
5211    (while (string-match "\\([^a-zA-Z0-9$_]\\)\\$[ \t]*\n" string)
5212      (setq string (replace-match "\\1 " t nil string)))
5213    (while (string-match "\n" string)
5214      (setq string (replace-match " " t nil string)))
5215    ;; Match the name and type.
5216    (when (string-match
5217	   "\\<\\(pro\\|function\\)\\>\\s-+\\(\\([a-zA-Z0-9$_]+\\)::\\)?\\([a-zA-Z0-9$_]+\\)" string)
5218      (setq start (match-end 0))
5219      (setq type (downcase (match-string 1 string)))
5220      (if (match-beginning 3)
5221	  (setq class (match-string 3 string)))
5222      (setq name (match-string 4 string)))
5223    ;; Match normal args and keyword args
5224    (while (string-match
5225	    ",\\s-*\\([a-zA-Z][a-zA-Z0-9$_]*\\|\\(_ref\\)?_extra\\)\\s-*\\(=\\)?"
5226	    string start)
5227      (setq start (match-end 0))
5228      (if (match-beginning 3)
5229	  (push (match-string 1 string) keywords)
5230	(push (match-string 1 string) args)))
5231    ;; Normalize and sort.
5232    (setq args (nreverse args))
5233    (setq keywords (sort keywords (lambda (a b)
5234				    (string< (downcase a) (downcase b)))))
5235    ;; Make and return the entry
5236    ;; We don't know which argument are optional, so this information
5237    ;; will not be contained in the calling sequence.
5238    (list name
5239	  (if (equal type "pro") 'pro 'fun)
5240	  class
5241	  (cond ((not (boundp 'idlwave-scanning-lib))
5242		 (list  'buffer (buffer-file-name)))
5243;		((string= (downcase (file-name-base (buffer-file-name))
5244;			  (downcase name))
5245;		 (list 'lib))
5246;		(t (cons 'lib (file-name-nondirectory (buffer-file-name))))
5247		(t (list 'user (file-name-nondirectory (buffer-file-name))
5248			 idlwave-scanning-lib-dir "UserLib")))
5249	  (concat
5250	   (if (string= type "function") "Result = " "")
5251	   (if class "Obj ->[%s::]" "")
5252	   "%s"
5253	   (if args
5254	       (concat
5255		(if (string= type "function") "(" ", ")
5256		(mapconcat 'identity args ", ")
5257		(if (string= type "function") ")" ""))))
5258	  (if keywords
5259	      (cons nil (mapcar 'list keywords)) ;No help file
5260	    nil))))
5261
5262
5263;;----- Scanning the user catalog -------------------
5264
5265(defun idlwave-sys-dir ()
5266  "Return the syslib directory, or a dummy that never matches."
5267  (cond
5268   ((and idlwave-system-directory
5269	 (not (string= idlwave-system-directory "")))
5270    idlwave-system-directory)
5271   ((getenv "IDL_DIR"))
5272   (t "@@@@@@@@")))
5273
5274
5275(defun idlwave-create-user-catalog-file (&optional arg)
5276  "Scan all files on selected dirs of IDL search path for routine information.
5277
5278A widget checklist will allow you to choose the directories.  Write
5279the result as a file `idlwave-user-catalog-file'.  When this file
5280exists, it will be automatically loaded to give routine information
5281about library routines.  With ARG, just rescan the same directories
5282as last time - so no widget will pop up."
5283  (interactive "P")
5284  ;; Make sure the file is loaded if it exists.
5285  (if (and (stringp idlwave-user-catalog-file)
5286	   (file-regular-p idlwave-user-catalog-file))
5287      (condition-case nil
5288	  (load-file idlwave-user-catalog-file)
5289	(error nil)))
5290  ;; Make sure the file name makes sense
5291  (unless (and (stringp idlwave-user-catalog-file)
5292	       (> (length idlwave-user-catalog-file) 0)
5293	       (file-accessible-directory-p
5294		(file-name-directory idlwave-user-catalog-file))
5295	       (not (string= "" (file-name-nondirectory
5296				 idlwave-user-catalog-file))))
5297    (error "`idlwave-user-catalog-file' does not point to a file in an accessible directory"))
5298
5299  (cond
5300    ;; Rescan the known directories
5301   ((and arg idlwave-path-alist
5302	 (consp (car idlwave-path-alist)))
5303    (idlwave-scan-user-lib-files idlwave-path-alist))
5304
5305   ;; Expand the directories from library-path and run the widget
5306   (idlwave-library-path
5307    (idlwave-display-user-catalog-widget
5308     (if idlwave-true-path-alist
5309	 ;; Propagate any flags on the existing path-alist
5310	 (mapcar (lambda (x)
5311		   (let ((path-entry (assoc (file-truename x)
5312					    idlwave-true-path-alist)))
5313		     (if path-entry
5314			 (cons x (cdr path-entry))
5315		       (list x))))
5316		 (idlwave-expand-path idlwave-library-path))
5317       (mapcar 'list (idlwave-expand-path idlwave-library-path)))))
5318
5319   ;; Ask the shell for the path and then run the widget
5320   (t
5321    (message "Asking the shell for IDL path...")
5322    (require 'idlw-shell)
5323    (idlwave-shell-send-command idlwave-shell-path-query
5324				'(idlwave-user-catalog-command-hook nil)
5325				'hide))))
5326
5327
5328;; Parse shell path information and select among it.
5329(defun idlwave-user-catalog-command-hook (&optional arg)
5330  ;; Command hook used by `idlwave-create-user-catalog-file'.
5331  (if arg
5332      ;; Scan immediately
5333      (idlwave-scan-user-lib-files idlwave-path-alist)
5334    ;; Set the path and display the widget
5335    (idlwave-shell-get-path-info 'no-write) ; set to something path-alist
5336    (idlwave-scan-library-catalogs "Locating library catalogs..." 'no-load)
5337    (idlwave-display-user-catalog-widget idlwave-path-alist)))
5338
5339(defconst idlwave-user-catalog-widget-help-string
5340  "This is the front-end to the creation of the IDLWAVE user catalog.
5341Please select the directories on IDL's search path from which you
5342would like to extract routine information, to be stored in the file:
5343
5344             %s
5345
5346If this is not the correct file, first set variable
5347`idlwave-user-catalog-file', and call this command again.
5348
5349N.B. Many libraries include pre-scanned catalog files
5350\(\".idlwave_catalog\").  These are marked with \"[LIB]\", and need
5351not be scanned.  You can scan your own libraries off-line using the
5352perl script `idlwave_catalog'.
5353
5354After selecting the directories, choose [Scan & Save] to scan the library
5355directories and save the routine info.
5356\n")
5357
5358(defvar idlwave-widget)
5359(defvar widget-keymap)
5360(defun idlwave-display-user-catalog-widget (dirs-list)
5361  "Create the widget to select IDL search path directories for scanning."
5362  (interactive)
5363  (require 'widget)
5364  (require 'wid-edit)
5365  (unless dirs-list
5366      (error "Don't know IDL's search path"))
5367
5368  (kill-buffer (get-buffer-create "*IDLWAVE Widget*"))
5369  (switch-to-buffer (get-buffer-create "*IDLWAVE Widget*"))
5370  (kill-all-local-variables)
5371  (make-local-variable 'idlwave-widget)
5372  (widget-insert (format idlwave-user-catalog-widget-help-string
5373			 idlwave-user-catalog-file))
5374
5375  (widget-create 'push-button
5376		 :notify 'idlwave-widget-scan-user-lib-files
5377		 "Scan & Save")
5378  (widget-insert "  ")
5379  (widget-create 'push-button
5380		 :notify 'idlwave-delete-user-catalog-file
5381		 "Delete File")
5382  (widget-insert "  ")
5383  (widget-create 'push-button
5384		 :notify
5385		 (lambda (&rest ignore)
5386                   (let ((path-list (widget-get idlwave-widget :path-dirs)))
5387                     (dolist (x path-list)
5388                       (unless (memq 'lib (cdr x))
5389                         (idlwave-path-alist-add-flag x 'user)))
5390                     (idlwave-display-user-catalog-widget path-list)))
5391		 "Select All Non-Lib")
5392  (widget-insert "  ")
5393  (widget-create 'push-button
5394		 :notify
5395		 (lambda (&rest ignore)
5396                   (let ((path-list (widget-get idlwave-widget :path-dirs)))
5397                     (dolist (x path-list)
5398                       (idlwave-path-alist-remove-flag x 'user))
5399                     (idlwave-display-user-catalog-widget path-list)))
5400		 "Deselect All")
5401  (widget-insert "  ")
5402  (widget-create 'push-button
5403		 :notify (lambda (&rest ignore)
5404			   (kill-buffer (current-buffer)))
5405		 "Quit")
5406  (widget-insert "\n\n")
5407
5408  (widget-insert "Select Directories: \n")
5409
5410  (setq idlwave-widget
5411	(apply 'widget-create
5412	       'checklist
5413	       :value  (delq nil (mapcar (lambda (x)
5414					   (if (memq 'user (cdr x))
5415					       (car x)))
5416					 dirs-list))
5417	       :greedy t
5418	       :tag "List of directories"
5419	       (mapcar (lambda (x)
5420			 (list 'item
5421			       (if (memq 'lib (cdr x))
5422				   (concat "[LIB] " (car x) )
5423				 (car x)))) dirs-list)))
5424  (widget-put idlwave-widget :path-dirs dirs-list)
5425  (widget-insert "\n")
5426  (use-local-map widget-keymap)
5427  (widget-setup)
5428  (goto-char (point-min))
5429  (delete-other-windows))
5430
5431(defun idlwave-delete-user-catalog-file (&rest ignore)
5432  (if (yes-or-no-p
5433       (format "Delete file %s " idlwave-user-catalog-file))
5434      (progn
5435	(delete-file idlwave-user-catalog-file)
5436	(message "%s has been deleted" idlwave-user-catalog-file))))
5437
5438(defun idlwave-widget-scan-user-lib-files (&rest ignore)
5439  ;; Call `idlwave-scan-user-lib-files' with data taken from the widget.
5440  (let* ((widget idlwave-widget)
5441	 (selected-dirs (widget-value widget))
5442	 (path-alist (widget-get widget :path-dirs))
5443	 (this-path-alist path-alist)
5444	 dir-entry)
5445    (while (setq dir-entry (pop this-path-alist))
5446      (if (member
5447	   (if (memq 'lib (cdr dir-entry))
5448	       (concat "[LIB] " (car dir-entry))
5449	     (car dir-entry))
5450	   selected-dirs)
5451	  (idlwave-path-alist-add-flag dir-entry 'user)
5452	(idlwave-path-alist-remove-flag dir-entry 'user)))
5453    (idlwave-scan-user-lib-files path-alist)))
5454
5455(defvar font-lock-mode)
5456(defun idlwave-scan-user-lib-files (path-alist)
5457  ;; Scan the PRO files in PATH-ALIST and store the info in the user catalog
5458  (let* ((idlwave-scanning-lib t)
5459	 (idlwave-scanning-lib-dir "")
5460	 (idlwave-completion-case nil)
5461	 dirs-alist dir files file)
5462    (setq idlwave-user-catalog-routines nil
5463	  idlwave-path-alist path-alist ; for library-path instead
5464	  idlwave-true-path-alist nil)
5465    (if idlwave-auto-write-paths (idlwave-write-paths))
5466    (with-current-buffer (get-buffer-create "*idlwave-scan.pro*")
5467      (idlwave-mode)
5468      (setq dirs-alist (reverse path-alist))
5469      (while (setq dir (pop dirs-alist))
5470	(when (memq 'user (cdr dir))	; Has it marked for scan?
5471	  (setq dir (car dir))
5472	  (setq idlwave-scanning-lib-dir dir)
5473	  (when (file-directory-p dir)
5474	    (setq files (directory-files dir 'full "\\.[pP][rR][oO]\\'"))
5475	    (while (setq file (pop files))
5476	      (when (file-regular-p file)
5477		(if (not (file-readable-p file))
5478		    (message "Skipping %s (no read permission)" file)
5479		  (message "Scanning %s..." file)
5480		  (erase-buffer)
5481		  (insert-file-contents file 'visit)
5482		  (setq idlwave-user-catalog-routines
5483			(append (idlwave-get-routine-info-from-buffers
5484				 (list (current-buffer)))
5485				idlwave-user-catalog-routines)))))))))
5486    (message "Creating user catalog file...")
5487    (kill-buffer "*idlwave-scan.pro*")
5488    (kill-buffer (get-buffer-create "*IDLWAVE Widget*"))
5489    (with-temp-buffer
5490      (insert ";; IDLWAVE user catalog file\n")
5491      (insert (format ";; Created %s\n\n" (current-time-string)))
5492
5493      ;; Define the routine info list
5494      (insert "\n(setq idlwave-user-catalog-routines\n    '(")
5495      (let ((standard-output (current-buffer)))
5496	(mapc (lambda (x)
5497		(insert "\n    ")
5498		(prin1 x)
5499		(goto-char (point-max)))
5500	      idlwave-user-catalog-routines))
5501      (insert (format "))\n\n;;; %s ends here\n"
5502		      (file-name-nondirectory idlwave-user-catalog-file)))
5503      (write-region nil nil idlwave-user-catalog-file)))
5504  (message "Creating user catalog file...done")
5505  (message "Info for %d routines saved in %s"
5506	   (length idlwave-user-catalog-routines)
5507	   idlwave-user-catalog-file)
5508  (sit-for 2)
5509  (idlwave-update-routine-info t))
5510
5511(defun idlwave-read-paths ()
5512  (if (and (stringp idlwave-path-file)
5513	   (file-regular-p idlwave-path-file))
5514      (condition-case nil
5515	  (load idlwave-path-file t t t)
5516	(error nil))))
5517
5518(defun idlwave-write-paths ()
5519  (interactive)
5520  (when (and idlwave-path-alist idlwave-system-directory)
5521    (with-temp-buffer
5522      (insert ";; IDLWAVE paths\n")
5523      (insert (format ";; Created %s\n\n" (current-time-string)))
5524    ;; Define the variable which knows the value of "!DIR"
5525      (insert (format "\n(setq idlwave-system-directory \"%s\")\n"
5526		      idlwave-system-directory))
5527
5528      ;; Define the variable which contains a list of all scanned directories
5529      (insert "\n(setq idlwave-path-alist\n    '(")
5530      (let ((standard-output (current-buffer)))
5531	(mapc (lambda (x)
5532		(insert "\n      ")
5533		(prin1 x)
5534		(goto-char (point-max)))
5535	      idlwave-path-alist))
5536      (insert "))\n")
5537      (write-region nil nil idlwave-path-file))))
5538
5539(defun idlwave-expand-path (path &optional default-dir)
5540  ;; Expand parts of path starting with '+' recursively into directory list.
5541  ;; Relative recursive path elements are expanded relative to DEFAULT-DIR.
5542  (message "Expanding path...")
5543  (let (path1 dir recursive)
5544    (while (setq dir (pop path))
5545      (if (setq recursive (string= (substring dir 0 1) "+"))
5546	  (setq dir (substring dir 1)))
5547      (if (and recursive
5548	       (not (file-name-absolute-p dir)))
5549	  (setq dir (expand-file-name dir default-dir)))
5550      (if recursive
5551	  ;; Expand recursively
5552	  (setq path1 (append (idlwave-recursive-directory-list dir) path1))
5553	;; Keep unchanged
5554	(push dir path1)))
5555    (message "Expanding path...done")
5556    (nreverse path1)))
5557
5558(defun idlwave-recursive-directory-list (dir)
5559  ;; Return a list of all directories below DIR, including DIR itself
5560  (let ((path (list dir)) path1 file files)
5561    (while (setq dir (pop path))
5562      (when (file-directory-p dir)
5563	(setq files (nreverse (directory-files dir t "[^.]")))
5564	(while (setq file (pop files))
5565	  (if (file-directory-p file)
5566	      (push (file-name-as-directory file) path)))
5567	(push dir path1)))
5568    path1))
5569
5570
5571;;----- Scanning the library catalogs ------------------
5572
5573
5574
5575
5576(defun idlwave-scan-library-catalogs (&optional message-base no-load)
5577  "Scan for library catalog files (.idlwave_catalog) and ingest.
5578
5579All directories on `idlwave-path-alist' (or `idlwave-library-path'
5580instead, if present) are searched.  Print MESSAGE-BASE along with the
5581libraries being loaded, if passed, and skip loading/normalizing if
5582NO-LOAD is non-nil.  The variable `idlwave-use-library-catalogs' can
5583be set to nil to disable library catalog scanning."
5584  (when idlwave-use-library-catalogs
5585    (let ((dirs
5586	   (if idlwave-library-path
5587	       (idlwave-expand-path idlwave-library-path)
5588	     (mapcar 'car idlwave-path-alist)))
5589	  (old-libname "")
5590	  dir-entry dir catalog all-routines)
5591      (if message-base (message "%s" message-base))
5592      (while (setq dir (pop dirs))
5593	(catch 'continue
5594	  (when (file-readable-p
5595		 (setq catalog (expand-file-name ".idlwave_catalog" dir)))
5596	    (unless no-load
5597	      (setq idlwave-library-catalog-routines nil)
5598	      ;; Load the catalog file
5599	      (condition-case nil
5600		  (load catalog t t t)
5601		(error (throw 'continue t)))
5602	      (when (and
5603		     message-base
5604		     (not (string= idlwave-library-catalog-libname
5605				   old-libname)))
5606		(message "%s%s" message-base idlwave-library-catalog-libname)
5607		(setq old-libname idlwave-library-catalog-libname))
5608	      (when idlwave-library-catalog-routines
5609		(setq all-routines
5610		      (append
5611		       (idlwave-sintern-rinfo-list
5612			idlwave-library-catalog-routines 'sys dir)
5613		       all-routines))))
5614
5615	    ;;  Add a 'lib flag if on path-alist
5616	    (when (and idlwave-path-alist
5617		       (setq dir-entry (assoc dir idlwave-path-alist)))
5618	      (idlwave-path-alist-add-flag dir-entry 'lib)))))
5619      (unless no-load (setq idlwave-library-catalog-routines all-routines))
5620      (if message-base (message "%sdone" message-base)))))
5621
5622;;----- Communicating with the Shell -------------------
5623
5624;; First, here is the idl program which can be used to query IDL for
5625;; defined routines.
5626(defconst idlwave-routine-info.pro
5627  "
5628;; START OF IDLWAVE SUPPORT ROUTINES
5629pro idlwave_print_safe,item,limit
5630  catch,err
5631  if err ne 0 then begin
5632     print,'Could not print item.'
5633     return
5634  endif
5635  if n_elements(item) gt limit then $
5636     print,item[0:limit-1],'<... truncated at ',strtrim(limit,2),' elements>' $
5637  else print,item
5638end
5639
5640pro idlwave_print_info_entry,name,func=func,separator=sep
5641  ;; See if it's an object method
5642  if name eq '' then return
5643  func    = keyword_set(func)
5644  methsep = strpos(name,'::')
5645  meth    = methsep ne -1
5646
5647  ;; Get routine info
5648  pars   = routine_info(name,/parameters,functions=func)
5649  source = routine_info(name,/source,functions=func)
5650  nargs  = pars.num_args
5651  nkw    = pars.num_kw_args
5652  if nargs gt 0 then args = pars.args
5653  if nkw   gt 0 then kwargs = pars.kw_args
5654
5655  ;; Trim the class, and make the name
5656  if meth then begin
5657      class = strmid(name,0,methsep)
5658      name  = strmid(name,methsep+2,strlen(name)-1)
5659      if nargs gt 0 then begin
5660          ;; remove the self argument
5661          wh = where(args ne 'SELF',nargs)
5662          if nargs gt 0 then args = args[wh]
5663      endif
5664  endif else begin
5665      ;; No class, just a normal routine.
5666      class = \"\"
5667  endelse
5668
5669  ;; Calling sequence
5670  cs = \"\"
5671  if func then cs = 'Result = '
5672  if meth then cs = cs + 'Obj -> [' + '%s' + '::]'
5673  cs = cs + '%s'
5674  if func then cs = cs + '(' else if nargs gt 0 then cs = cs + ', '
5675  if nargs gt 0 then begin
5676      for j=0,nargs-1 do begin
5677          cs = cs + args[j]
5678          if j lt nargs-1 then cs = cs + ', '
5679      endfor
5680  end
5681  if func then cs = cs + ')'
5682  ;; Keyword arguments
5683  kwstring = ''
5684  if nkw gt 0 then begin
5685      for j=0,nkw-1 do begin
5686          kwstring = kwstring + ' ' + kwargs[j]
5687      endfor
5688  endif
5689
5690  ret=(['IDLWAVE-PRO','IDLWAVE-FUN'])[func]
5691
5692  print,ret + ': ' + name + sep + class + sep + source[0].path  $
5693    + sep + cs + sep + kwstring
5694end
5695
5696pro idlwave_routine_info,file
5697  on_error,1
5698  sep = '<@>'
5699  print,'>>>BEGIN OF IDLWAVE ROUTINE INFO (\"' + sep + '\" IS THE SEPARATOR)'
5700  all = routine_info()
5701  fileQ=n_elements(file) ne 0
5702  if fileQ then file=strtrim(file,2)
5703  for i=0L,n_elements(all)-1L do begin
5704     if fileQ then begin
5705        if (routine_info(all[i],/SOURCE)).path eq file then $
5706           idlwave_print_info_entry,all[i],separator=sep
5707     endif else idlwave_print_info_entry,all[i],separator=sep
5708  endfor
5709  all = routine_info(/functions)
5710  for i=0L,n_elements(all)-1L do begin
5711     if fileQ then begin
5712        if (routine_info(all[i],/FUNCTIONS,/SOURCE)).path eq file then $
5713           idlwave_print_info_entry,all[i],separator=sep,/FUNC
5714     endif else idlwave_print_info_entry,all[i],separator=sep,/FUNC
5715  endfor
5716  print,'>>>END OF IDLWAVE ROUTINE INFO'
5717end
5718
5719pro idlwave_get_sysvars
5720  on_error,1
5721  catch,error_status
5722  if error_status ne 0 then begin
5723      print, 'Cannot get info about system variables'
5724  endif else begin
5725      help,/brief,output=s,/system_variables  ; ? unsafe use of OUTPUT=
5726      s = strtrim(strjoin(s,' ',/single),2)   ; make one line
5727      v = strsplit(s,' +',/regex,/extract)    ; get variables
5728      for i=0L,n_elements(v)-1 do begin
5729          t = ['']                            ; get tag list
5730          a=execute('if n_tags('+v[i]+') gt 0 then t=tag_names('+v[i]+')')
5731          print, 'IDLWAVE-SYSVAR: '+v[i]+' '+strjoin(t,' ',/single)
5732      endfor
5733  endelse
5734end
5735
5736pro idlwave_get_class_tags, class
5737  res = execute('tags=tag_names({'+class+'})')
5738  if res then print,'IDLWAVE-CLASS-TAGS: '+class+' '+strjoin(tags,' ',/single)
5739end
5740;; END OF IDLWAVE SUPPORT ROUTINES
5741"
5742  "The IDL programs to get info from the shell.")
5743
5744(defvar idlwave-idlwave_routine_info-compiled nil
5745  "Remember if the routine info procedure is already compiled.")
5746
5747(defvar idlwave-shell-temp-pro-file)
5748(defvar idlwave-shell-temp-rinfo-save-file)
5749
5750(defun idlwave-shell-compile-helper-routines (&optional wait)
5751  (unless (and idlwave-idlwave_routine_info-compiled
5752	       (file-readable-p (idlwave-shell-temp-file 'rinfo)))
5753    (with-current-buffer (idlwave-find-file-noselect
5754                          (idlwave-shell-temp-file 'pro))
5755      (erase-buffer)
5756      (insert idlwave-routine-info.pro)
5757      (save-buffer 0))
5758    (idlwave-shell-send-command
5759     (concat ".run \"" idlwave-shell-temp-pro-file "\"")
5760     nil 'hide wait)
5761    (idlwave-shell-send-command
5762     (format "save,'idlwave_print_safe','idlwave_routine_info','idlwave_print_info_entry','idlwave_get_class_tags','idlwave_get_sysvars',FILE='%s',/ROUTINES"
5763	     (idlwave-shell-temp-file 'rinfo))
5764     nil 'hide)
5765    (setq idlwave-idlwave_routine_info-compiled t))
5766
5767  ;; Restore if necessary.  Must use execute to hide lame routine_info
5768  ;; errors on undefined routine
5769  (idlwave-shell-send-command
5770   (format "if execute(\"_v=routine_info('idlwave_routine_info',/SOURCE)\") eq 0 then restore,'%s' else if _v.path eq '' then restore,'%s'"
5771	   idlwave-shell-temp-rinfo-save-file
5772	   idlwave-shell-temp-rinfo-save-file)
5773   nil 'hide))
5774
5775
5776(defun idlwave-shell-update-routine-info (&optional quiet run-hooks wait file)
5777  "Query the shell for routine_info of compiled modules and update the lists."
5778  ;; Save and compile the procedure.  The compiled procedure is then
5779  ;; saved into an IDL SAVE file, to allow for fast RESTORE.  We may
5780  ;; need to test for and possibly RESTORE the procedure each time we
5781  ;; use it, since the user may have killed or redefined it.  In
5782  ;; particular, .RESET_SESSION will kill all user procedures.  If
5783  ;; FILE is set, only update routine info for routines in that file.
5784
5785  (idlwave-shell-compile-helper-routines wait)
5786  ; execute the routine_info procedure, and analyze the output
5787  (idlwave-shell-send-command
5788   (format "idlwave_routine_info%s" (if file (concat ",'" file "'") ""))
5789   `(progn
5790      (idlwave-shell-routine-info-filter)
5791      (idlwave-concatenate-rinfo-lists ,quiet ,run-hooks))
5792   'hide wait))
5793
5794;; ---------------------------------------------------------------------------
5795;;
5796;; Completion and displaying routine calling sequences
5797
5798(defvar idlwave-completion-help-info nil)
5799(defvar idlwave-completion-help-links nil)
5800(defvar idlwave-current-obj_new-class nil)
5801(defvar idlwave-complete-special nil)
5802(defvar method-selector)
5803(defvar class-selector)
5804(defvar type-selector)
5805(defvar super-classes)
5806
5807(defun idlwave-complete (&optional arg module class)
5808  "Complete a function, procedure or keyword name at point.
5809This function is smart and figures out what can be completed
5810at this point.
5811- At the beginning of a statement it completes procedure names.
5812- In the middle of a statement it completes function names.
5813- After a `(' or `,' in the argument list of a function or procedure,
5814  it completes a keyword of the relevant function or procedure.
5815- In the first arg of `OBJ_NEW', it completes a class name.
5816
5817When several completions are possible, a list will be displayed in
5818the *Completions* buffer.  If this list is too long to fit into the
5819window, scrolling can be achieved by repeatedly pressing
5820\\[idlwave-complete].
5821
5822The function also knows about object methods.  When it needs a class
5823name, the action depends upon `idlwave-query-class', which see.  You
5824can force IDLWAVE to ask you for a class name with a
5825\\[universal-argument] prefix argument to this command.
5826
5827See also the variables `idlwave-keyword-completion-adds-equal' and
5828`idlwave-function-completion-adds-paren'.
5829
5830The optional ARG can be used to specify the completion type in order
5831to override IDLWAVE's idea of what should be completed at point.
5832Possible values are:
5833
58340  <=>  query for the completion type
58351  <=>  `procedure'
58362  <=>  `procedure-keyword'
58373  <=>  `function'
58384  <=>  `function-keyword'
58395  <=>  `procedure-method'
58406  <=>  `procedure-method-keyword'
58417  <=>  `function-method'
58428  <=>  `function-method-keyword'
58439  <=>  `class'
5844
5845As a special case, the universal argument C-u forces completion of
5846function names in places where the default would be a keyword.
5847
5848Two prefix argument, C-u C-u, prompts for a regexp by which to limit
5849completion.
5850
5851For Lisp programmers only:
5852When we force a keyword, optional argument MODULE can contain the module name.
5853When we force a method or a method keyword, CLASS can specify the class."
5854  (interactive "P")
5855  (idlwave-routines)
5856  (let* ((where-list
5857	  (if (and arg
5858		   (or (and (integerp arg) (not (equal arg '(16))))
5859		       (symbolp arg)))
5860	      (idlwave-make-force-complete-where-list arg module class)
5861	    (idlwave-where)))
5862	 (what (nth 2 where-list))
5863	 (idlwave-force-class-query (equal arg '(4)))
5864	 (completion-regexp-list
5865	  (if (equal arg '(16))
5866	      (list (read-string (concat "Completion Regexp: "))))))
5867
5868    (if (and module (string-match "::" module))
5869	(setq class (substring module 0 (match-beginning 0))
5870	      module (substring module (match-end 0))))
5871
5872    (cond
5873
5874     ((and (null arg)
5875	   (eq (car-safe last-command) 'idlwave-display-completion-list)
5876	   (get-buffer-window "*Completions*"))
5877      (setq this-command last-command)
5878      (idlwave-scroll-completions))
5879
5880     ;; Complete a filename in quotes
5881     ((and (idlwave-in-quote)
5882	   (not (eq what 'class)))
5883      (idlwave-complete-filename))
5884
5885     ;; Check for any special completion functions
5886     ((and idlwave-complete-special
5887	   (idlwave-call-special idlwave-complete-special)))
5888
5889     ((null what)
5890      (error "Nothing to complete here"))
5891
5892     ;; Complete a class
5893     ((eq what 'class)
5894      (setq idlwave-completion-help-info '(class))
5895      (idlwave-complete-class))
5896
5897     ((eq what 'procedure)
5898      ;; Complete a procedure name
5899      (let* ((cw-list (nth 3 where-list))
5900	     (class-selector (idlwave-determine-class cw-list 'pro))
5901	     (super-classes (unless (idlwave-explicit-class-listed cw-list)
5902			      (idlwave-all-class-inherits class-selector)))
5903	     (isa (concat "procedure" (if class-selector "-method" "")))
5904	     (type-selector 'pro))
5905	(setq idlwave-completion-help-info
5906	      (list 'routine nil type-selector class-selector nil super-classes))
5907	(idlwave-complete-in-buffer
5908	 'procedure (if class-selector 'method 'routine)
5909	 (idlwave-routines) 'idlwave-selector
5910	 (format "Select a %s name%s"
5911		 isa
5912		 (if class-selector
5913		     (format " (class is %s)"
5914			     (if (eq class-selector t)
5915				 "unknown" class-selector))
5916		   ""))
5917	 isa
5918	 'idlwave-attach-method-classes 'idlwave-add-file-link-selector)))
5919
5920     ((eq what 'function)
5921      ;; Complete a function name
5922      (let* ((cw-list (nth 3 where-list))
5923	     (class-selector (idlwave-determine-class cw-list 'fun))
5924	     (super-classes (unless (idlwave-explicit-class-listed cw-list)
5925			      (idlwave-all-class-inherits class-selector)))
5926	     (isa (concat "function" (if class-selector "-method" "")))
5927	     (type-selector 'fun))
5928	(setq idlwave-completion-help-info
5929	      (list 'routine nil type-selector class-selector nil super-classes))
5930	(idlwave-complete-in-buffer
5931	 'function (if class-selector 'method 'routine)
5932	 (idlwave-routines) 'idlwave-selector
5933	 (format "Select a %s name%s"
5934		 isa
5935		 (if class-selector
5936		     (format " (class is %s)"
5937			     (if (eq class-selector t)
5938				 "unknown" class-selector))
5939		   ""))
5940	 isa
5941	 'idlwave-attach-method-classes 'idlwave-add-file-link-selector)))
5942
5943     ((and (memq what '(procedure-keyword function-keyword)) ; Special Case
5944	   (equal arg '(4)))
5945      (idlwave-complete 3))
5946
5947     ((eq what 'procedure-keyword)
5948      ;; Complete a procedure keyword
5949      (let* ((where (nth 3 where-list))
5950	     (name  (car where))
5951	     (method-selector name)
5952	     (type-selector 'pro)
5953	     (class (idlwave-determine-class where 'pro))
5954	     (class-selector class)
5955	     (super-classes (idlwave-all-class-inherits class-selector))
5956	     (isa (format "procedure%s-keyword" (if class "-method" "")))
5957	     (entry (idlwave-best-rinfo-assq
5958		     name 'pro class (idlwave-routines)))
5959	     (system (if entry (eq (car (nth 3 entry)) 'system)))
5960	     (list (idlwave-entry-keywords entry 'do-link)))
5961	(unless (or entry (eq class t))
5962	  (error "Nothing known about procedure %s"
5963		 (idlwave-make-full-name class name)))
5964	(setq list (idlwave-fix-keywords name 'pro class list
5965					 super-classes system))
5966	(unless list (error "No keywords available for procedure %s"
5967			    (idlwave-make-full-name class name)))
5968	(setq idlwave-completion-help-info
5969	      (list 'keyword name type-selector class-selector entry super-classes))
5970	(idlwave-complete-in-buffer
5971	 'keyword 'keyword list nil
5972	 (format "Select keyword for procedure %s%s"
5973		 (idlwave-make-full-name class name)
5974		 (if (or (member '("_EXTRA") list)
5975			 (member '("_REF_EXTRA") list))
5976		     " (note _EXTRA)" ""))
5977	 isa
5978	 'idlwave-attach-keyword-classes)))
5979
5980     ((eq what 'function-keyword)
5981      ;; Complete a function keyword
5982      (let* ((where (nth 3 where-list))
5983	     (name  (car where))
5984	     (method-selector name)
5985	     (type-selector 'fun)
5986	     (class (idlwave-determine-class where 'fun))
5987	     (class-selector class)
5988	     (super-classes (idlwave-all-class-inherits class-selector))
5989	     (isa (format "function%s-keyword" (if class "-method" "")))
5990	     (entry (idlwave-best-rinfo-assq
5991		     name 'fun class (idlwave-routines)))
5992	     (system (if entry (eq (car (nth 3 entry)) 'system)))
5993	     (list (idlwave-entry-keywords entry 'do-link))
5994	     msg-name)
5995	(unless (or entry (eq class t))
5996	  (error "Nothing known about function %s"
5997		 (idlwave-make-full-name class name)))
5998	(setq list (idlwave-fix-keywords name 'fun class list
5999					 super-classes system))
6000	;; OBJ_NEW: Messages mention the proper Init method
6001	(setq msg-name (if (and (null class)
6002				(string= (upcase name) "OBJ_NEW"))
6003			   (concat idlwave-current-obj_new-class
6004				   "::Init (via OBJ_NEW)")
6005			 (idlwave-make-full-name class name)))
6006	(unless list (error "No keywords available for function %s"
6007			    msg-name))
6008	(setq idlwave-completion-help-info
6009	      (list 'keyword name type-selector class-selector nil super-classes))
6010	(idlwave-complete-in-buffer
6011	 'keyword 'keyword list nil
6012	 (format "Select keyword for function %s%s" msg-name
6013		 (if (or (member '("_EXTRA") list)
6014			 (member '("_REF_EXTRA") list))
6015		     " (note _EXTRA)" ""))
6016	 isa
6017	 'idlwave-attach-keyword-classes)))
6018
6019     (t (error "This should not happen (idlwave-complete)")))))
6020
6021(defvar idlwave-complete-special nil
6022  "List of special completion functions.
6023These functions are called for each completion.  Each function must
6024check if its own special completion context is present.  If yes, it
6025should use `idlwave-complete-in-buffer' to do some completion and
6026return t.  If such a function returns t, *no further* attempts to
6027complete other contexts will be done.  If the function returns nil,
6028other completions will be tried.")
6029
6030(defun idlwave-call-special (functions &rest args)
6031  (let ((funcs functions)
6032	fun ret)
6033    (catch 'exit
6034      (while (setq fun (pop funcs))
6035	(if (setq ret (apply fun args))
6036	    (throw 'exit ret)))
6037      nil)))
6038
6039(defun idlwave-make-force-complete-where-list (what &optional module class)
6040  ;; Return an artificial WHERE specification to force the completion
6041  ;; routine to complete a specific item independent of context.
6042  ;; WHAT is the prefix arg of `idlwave-complete', see there for details.
6043  ;; MODULE and CLASS can be used to specify the routine name and class.
6044  ;; The class name will also be found in MODULE if that is like "class::mod".
6045  (let* ((what-list '(("procedure") ("procedure-keyword")
6046		      ("function") ("function-keyword")
6047		      ("procedure-method") ("procedure-method-keyword")
6048		      ("function-method") ("function-method-keyword")
6049		      ("class")))
6050	 (module (idlwave-sintern-routine-or-method module class))
6051	 (class (idlwave-sintern-class class))
6052	 (what (cond
6053		((equal what 0)
6054		 (setq what
6055		       (intern (completing-read
6056				"Complete what? " what-list nil t))))
6057		((integerp what)
6058		 (setq what (intern (car (nth (1- what) what-list)))))
6059		((and what
6060		      (symbolp what)
6061		      (assoc (symbol-name what) what-list))
6062		 what)
6063		(t (error "Invalid WHAT"))))
6064	 (nil-list '(nil nil nil nil))
6065	 (class-list (list nil nil (or class t) nil)))
6066
6067    (cond
6068
6069     ((eq what 'procedure)
6070      (list nil-list nil-list 'procedure nil-list nil))
6071
6072     ((eq what 'procedure-keyword)
6073      (let* ((class-selector nil)
6074	     (super-classes nil)
6075	     (type-selector 'pro)
6076	     (pro (or module
6077		      (idlwave-completing-read
6078		       "Procedure: " (idlwave-routines) 'idlwave-selector))))
6079	(setq pro (idlwave-sintern-routine pro))
6080	(list nil-list nil-list 'procedure-keyword
6081	      (list pro nil nil nil) nil)))
6082
6083     ((eq what 'function)
6084      (list nil-list nil-list 'function nil-list nil))
6085
6086     ((eq what 'function-keyword)
6087      (let* ((class-selector nil)
6088	     (super-classes nil)
6089	     (type-selector 'fun)
6090	     (func (or module
6091		       (idlwave-completing-read
6092			"Function: " (idlwave-routines) 'idlwave-selector))))
6093	(setq func (idlwave-sintern-routine func))
6094	(list nil-list nil-list 'function-keyword
6095	      (list func nil nil nil) nil)))
6096
6097     ((eq what 'procedure-method)
6098      (list nil-list nil-list 'procedure class-list nil))
6099
6100     ((eq what 'procedure-method-keyword)
6101      (let* ((class (idlwave-determine-class class-list 'pro))
6102	     (class-selector class)
6103	     (super-classes (idlwave-all-class-inherits class-selector))
6104	     (type-selector 'pro)
6105	     (pro (or module
6106		      (idlwave-completing-read
6107		       (format "Procedure in %s class: " class-selector)
6108		       (idlwave-routines) 'idlwave-selector))))
6109	(setq pro (idlwave-sintern-method pro))
6110	(list nil-list nil-list 'procedure-keyword
6111	      (list pro nil class nil) nil)))
6112
6113     ((eq what 'function-method)
6114      (list nil-list nil-list 'function class-list nil))
6115
6116     ((eq what 'function-method-keyword)
6117      (let* ((class (idlwave-determine-class class-list 'fun))
6118	     (class-selector class)
6119	     (super-classes (idlwave-all-class-inherits class-selector))
6120	     (type-selector 'fun)
6121	     (func (or module
6122		       (idlwave-completing-read
6123			(format "Function in %s class: " class-selector)
6124			(idlwave-routines) 'idlwave-selector))))
6125	(setq func (idlwave-sintern-method func))
6126	(list nil-list nil-list 'function-keyword
6127	      (list func nil class nil) nil)))
6128
6129     ((eq what 'class)
6130      (list nil-list nil-list 'class nil-list nil))
6131
6132     (t (error "Invalid value for WHAT")))))
6133
6134(defun idlwave-completing-read (&rest args)
6135  ;; Completing read, case insensitive
6136  (let ((old-value (default-value 'completion-ignore-case)))
6137    (unwind-protect
6138	(progn
6139	  (setq-default completion-ignore-case t)
6140	  (apply 'completing-read args))
6141      (setq-default completion-ignore-case old-value))))
6142
6143(defvar idlwave-shell-default-directory)
6144(defun idlwave-complete-filename ()
6145  "Use the comint stuff to complete a file name."
6146  (require 'comint)
6147  (let* ((comint-file-name-chars "~/A-Za-z0-9+@:_.$#%={}\\-")
6148	 (comint-completion-addsuffix nil)
6149	 (default-directory
6150	   (if (and (boundp 'idlwave-shell-default-directory)
6151		    (stringp idlwave-shell-default-directory)
6152		    (file-directory-p idlwave-shell-default-directory))
6153	       idlwave-shell-default-directory
6154	     default-directory)))
6155    (comint-dynamic-complete-filename)))
6156
6157(defun idlwave-make-full-name (class name)
6158  ;; Make a fully qualified module name including the class name
6159  (concat (if class (format "%s::" class) "") name))
6160
6161(defun idlwave-rinfo-assoc (name type class list)
6162  "Like `idlwave-rinfo-assq', but sintern strings first."
6163  (idlwave-rinfo-assq
6164   (idlwave-sintern-routine-or-method name class)
6165   type (idlwave-sintern-class class) list))
6166
6167(defun idlwave-rinfo-assq (name type class list)
6168  ;; Works like assq, but also checks type and class
6169  (catch 'exit
6170    (let (match)
6171      (while (setq match (assq name list))
6172	(and (or (eq type t)
6173		 (eq (nth 1 match) type))
6174	     (eq (nth 2 match) class)
6175	     (throw 'exit match))
6176	(setq list (cdr (memq match list)))))))
6177
6178(defun idlwave-rinfo-assq-any-class (name type class list)
6179  ;; Return the first matching method on the inheritance list
6180  (let* ((classes (cons class (idlwave-all-class-inherits class)))
6181	 class rtn)
6182    (while classes
6183      (if (setq rtn (idlwave-rinfo-assq name type (pop classes) list))
6184	  (setq classes nil)))
6185    rtn))
6186
6187(defun idlwave-best-rinfo-assq (name type class list &optional with-file
6188				     keep-system)
6189  "Like `idlwave-rinfo-assq', but get all twins and sort, then return first.
6190If WITH-FILE is passed, find the best rinfo entry with a file
6191included.  If KEEP-SYSTEM is set, don't prune system for compiled
6192syslib files."
6193  (let ((twins (idlwave-routine-twins
6194		(idlwave-rinfo-assq-any-class name type class list)
6195		list))
6196	syslibp)
6197    (when (> (length twins) 1)
6198      (setq twins (sort twins 'idlwave-routine-entry-compare-twins))
6199      (if (and (null keep-system)
6200	       (eq 'system (car (nth 3 (car twins))))
6201	       (setq syslibp (idlwave-any-syslib (cdr twins)))
6202	       (not (equal 1 syslibp)))
6203	  ;; Its a compiled syslib, so we need to remove the system entry
6204	  (setq twins (cdr twins)))
6205      (if with-file
6206	  (setq twins (delq nil
6207			    (mapcar (lambda (x)
6208				      (if (nth 1 (nth 3 x)) x))
6209				    twins)))))
6210    (car twins)))
6211
6212(defun idlwave-best-rinfo-assoc (name type class list &optional with-file
6213				     keep-system)
6214  "Like `idlwave-best-rinfo-assq', but sintern strings first."
6215  (idlwave-best-rinfo-assq
6216   (idlwave-sintern-routine-or-method name class)
6217   type (idlwave-sintern-class class) list with-file keep-system))
6218
6219(defun idlwave-any-syslib (entries)
6220  "Does the entry list ENTRIES contain a syslib entry?
6221If yes, return the index (>=1)."
6222  (let (file (cnt 0))
6223    (catch 'exit
6224      (while entries
6225	(cl-incf cnt)
6226	(setq file (idlwave-routine-source-file (nth 3 (car entries))))
6227	(if (and file (idlwave-syslib-p file))
6228	    (throw 'exit cnt)
6229	  (setq entries (cdr entries))))
6230      nil)))
6231
6232(defun idlwave-all-assq (key list)
6233  "Return a list of all associations of Key in LIST."
6234  (let (rtn elt)
6235    (while (setq elt (assq key list))
6236      (push elt rtn)
6237      (setq list (cdr (memq elt list))))
6238    (nreverse rtn)))
6239
6240(defun idlwave-all-method-classes (method &optional type)
6241  "Return all classes which have a method METHOD.
6242TYPE is `fun' or `pro'.
6243When TYPE is not specified, both procedures and functions will be considered."
6244  (if (null method)
6245      (mapcar 'car (idlwave-class-alist))
6246    (let (rtn)
6247      (mapc (lambda (x)
6248	      (and (nth 2 x)
6249		   (or (not type)
6250		       (eq type (nth 1 x)))
6251		   (push (nth 2 x) rtn)))
6252	    (idlwave-all-assq method (idlwave-routines)))
6253      (idlwave-uniquify rtn))))
6254
6255(defun idlwave-all-method-keyword-classes (method keyword &optional type)
6256  "Return all classes which have a method METHOD with keyword KEYWORD.
6257TYPE is `fun' or `pro'.
6258When TYPE is not specified, both procedures and functions will be considered."
6259  (if (or (null method)
6260	  (null keyword))
6261      nil
6262    (let (rtn)
6263      (mapc (lambda (x)
6264	      (and (nth 2 x)		; non-nil class
6265		   (or (not type)	; correct or unspecified type
6266		       (eq type (nth 1 x)))
6267		   (assoc keyword (idlwave-entry-keywords x))
6268		   (push (nth 2 x) rtn)))
6269	    (idlwave-all-assq method (idlwave-routines)))
6270      (idlwave-uniquify rtn))))
6271
6272(defun idlwave-members-only (list club)
6273  "Return list of all elements in LIST which are also in CLUB."
6274  (let (rtn)
6275    (while list
6276      (if (member (car list) club)
6277	  (setq rtn (cons (car list) rtn)))
6278      (setq list (cdr list)))
6279    (nreverse rtn)))
6280
6281(defun idlwave-nonmembers-only (list club)
6282  "Return list of all elements in LIST which are not in CLUB."
6283  (let (rtn)
6284    (while list
6285      (if (member (car list) club)
6286	  nil
6287	(setq rtn (cons (car list) rtn)))
6288      (setq list (cdr list)))
6289    (nreverse rtn)))
6290
6291(defun idlwave-explicit-class-listed (info)
6292  "Return whether or not the class is listed explicitly, ala a->b::c.
6293INFO is as returned by `idlwave-what-function' or `-procedure'."
6294  (let ((apos (nth 3 info)))
6295    (if apos
6296	(save-excursion (goto-char apos)
6297			(looking-at "->[a-zA-Z][a-zA-Z0-9$_]*::")))))
6298
6299(defvar idlwave-determine-class-special nil
6300  "List of special functions for determining class.
6301Must accept two arguments: `apos' and `info'.")
6302
6303(defun idlwave-determine-class (info type)
6304  ;; Determine the class of a routine call.
6305  ;; INFO is the `cw-list' structure as returned by idlwave-where.
6306  ;; The second element in this structure is the class.  When nil, we
6307  ;; return nil.  When t, try to get the class from text properties at
6308  ;; the arrow.  When the object is "self", we use the class of the
6309  ;; current routine.  otherwise prompt the user for a class name.
6310  ;; Also stores the selected class as a text property at the arrow.
6311  ;; TYPE is 'fun or 'pro.
6312  (let* ((class (nth 2 info))
6313	 (apos (nth 3 info))
6314	 (nassoc (assoc (if (stringp (car info))
6315			    (upcase (car info))
6316			  (car info))
6317			idlwave-query-class))
6318	 (dassoc (assq (if (car info) 'keyword-default 'method-default)
6319		       idlwave-query-class))
6320	 (query (cond (nassoc (cdr nassoc))
6321		      (dassoc (cdr dassoc))
6322		      (t t)))
6323	 (arrow (and apos (string= (buffer-substring apos (+ 2 apos)) "->")))
6324	 (is-self
6325	  (and arrow
6326	       (save-excursion (goto-char apos)
6327			       (forward-word-strictly -1)
6328			       (let ((case-fold-search t))
6329				 (looking-at "self\\>")))))
6330	 (force-query idlwave-force-class-query)
6331	 store special-class class-alist)
6332    (cond
6333     ((null class) nil)
6334     ((eq t class)
6335      ;; There is an object which would like to know its class
6336      (if (and arrow (get-text-property apos 'idlwave-class)
6337	       idlwave-store-inquired-class
6338	       (not force-query))
6339	  (setq class (get-text-property apos 'idlwave-class)
6340		class (idlwave-sintern-class class)))
6341      (if (and (eq t class) is-self)
6342	  (setq class (or (nth 2 (idlwave-current-routine)) class)))
6343
6344      ;; Before prompting, try any special class determination routines
6345      (when (and (eq t class)
6346		 idlwave-determine-class-special
6347		 (not force-query))
6348	(setq special-class
6349	      (idlwave-call-special idlwave-determine-class-special apos))
6350	(if special-class
6351	    (setq class (idlwave-sintern-class special-class)
6352		  store idlwave-store-inquired-class)))
6353
6354      ;; Prompt for a class, if we need to
6355      (when (and (eq class t)
6356		 (or force-query query))
6357	(setq class-alist
6358	      (mapcar 'list (idlwave-all-method-classes (car info) type)))
6359	(setq class
6360	      (idlwave-sintern-class
6361	       (cond
6362		((and (= (length class-alist) 0) (not force-query))
6363		 (error "No classes available with method %s" (car info)))
6364		((and (= (length class-alist) 1) (not force-query))
6365		 (car (car class-alist)))
6366		(t
6367		 (setq store idlwave-store-inquired-class)
6368		 (idlwave-completing-read
6369		  (format "Class%s: " (if (stringp (car info))
6370					  (format " for %s method %s"
6371						  type (car info))
6372					""))
6373		  class-alist nil nil nil 'idlwave-class-history))))))
6374
6375      ;; Store it, if requested
6376      (when (and class (not (eq t class)))
6377	;; We have a real class here
6378	(when (and store arrow)
6379	  (condition-case ()
6380	      (add-text-properties
6381	       apos (+ apos 2)
6382	       `(idlwave-class ,class face ,idlwave-class-arrow-face
6383			       rear-nonsticky t))
6384	    (error nil)))
6385	(setf (nth 2 info) class))
6386      ;; Return the class
6387      class)
6388     ;; Default as fallback
6389     (t class))))
6390
6391(defun idlwave-selector (a)
6392  (and (eq (nth 1 a) type-selector)
6393       (or (and (nth 2 a) (eq class-selector t))
6394	   (eq (nth 2 a) class-selector)
6395	   (memq (nth 2 a) super-classes))))
6396
6397(defun idlwave-add-file-link-selector (a)
6398  ;; Record a file link, if any, for the tested names during selection.
6399  (let ((sel (idlwave-selector a)) file)
6400    (if (and sel (setq file (idlwave-entry-has-help a)))
6401	(push (cons (car a) file) idlwave-completion-help-links))
6402    sel))
6403
6404
6405(defun idlwave-where ()
6406  "Find out where we are.
6407The return value is a list with the following stuff:
6408\(PRO-LIST FUNC-LIST COMPLETE-WHAT CW-LIST LAST-CHAR)
6409
6410PRO-LIST       (PRO POINT CLASS ARROW)
6411FUNC-LIST      (FUNC POINT CLASS ARROW)
6412COMPLETE-WHAT  a symbol indicating what kind of completion makes sense here
6413CW-LIST        (PRO-OR-FUNC POINT CLASS ARROW)  Like PRO-LIST, for what can
6414               be completed here.
6415LAST-CHAR      last relevant character before point (non-white non-comment,
6416               not part of current identifier or leading slash).
6417
6418In the lists, we have these meanings:
6419PRO:    Procedure name
6420FUNC:   Function name
6421POINT:  Where is this
6422CLASS:  What class has the routine (nil=no, t=is method, but class unknown)
6423ARROW:  Location of the arrow"
6424  (idlwave-routines)
6425  (let* (;(bos (save-excursion (idlwave-beginning-of-statement) (point)))
6426         (bos (save-excursion (idlwave-start-of-substatement 'pre) (point)))
6427 	 (func-entry (idlwave-what-function bos))
6428         (func (car func-entry))
6429         (func-class (nth 1 func-entry))
6430         (func-arrow (nth 2 func-entry))
6431	 (func-point (or (nth 3 func-entry) 0))
6432	 (func-level (or (nth 4 func-entry) 0))
6433	 (pro-entry (idlwave-what-procedure bos))
6434	 (pro (car pro-entry))
6435         (pro-class (nth 1 pro-entry))
6436         (pro-arrow (nth 2 pro-entry))
6437	 (pro-point (or (nth 3 pro-entry) 0))
6438	 (last-char (idlwave-last-valid-char))
6439         (case-fold-search t)
6440	 (match-string (buffer-substring bos (point)))
6441	 cw cw-mod cw-arrow cw-class cw-point)
6442    (if (< func-point pro-point) (setq func nil))
6443    (cond
6444     ((string-match "\\`[ \t]*\\(pro\\|function\\)[ \t]+[a-zA-Z0-9_]*\\'"
6445                    match-string)
6446      (setq cw 'class))
6447     ((string-match
6448       "\\`[ \t]*\\([a-zA-Z][a-zA-Z0-9$_]*\\)?\\'"
6449       (if (> pro-point 0)
6450	   (buffer-substring pro-point (point))
6451	 match-string))
6452      (setq cw 'procedure cw-class pro-class cw-point pro-point
6453	    cw-arrow pro-arrow))
6454     ((string-match "\\`[ \t]*\\(pro\\|function\\)\\>"
6455		    match-string)
6456      nil)
6457     ((string-match "OBJ_NEW([ \t]*['\"][a-zA-Z0-9$_]*\\'"
6458		    match-string)
6459      (setq cw 'class))
6460     ((string-match "\\<inherits\\s-+[a-zA-Z0-9$_]*\\'"
6461		    match-string)
6462      (setq cw 'class))
6463     ((and func
6464	   (> func-point pro-point)
6465	   (= func-level 1)
6466	   (memq last-char '(?\( ?,)))
6467      (setq cw 'function-keyword cw-mod func cw-point func-point
6468	    cw-class func-class cw-arrow func-arrow))
6469     ((and pro (eq last-char ?,))
6470      (setq cw 'procedure-keyword cw-mod pro cw-point pro-point
6471	    cw-class pro-class cw-arrow pro-arrow))
6472;     ((member last-char '(?\' ?\) ?\] ?!))
6473;      ;; after these chars, a function makes no sense
6474;      ;; FIXME: I am sure there can be more in this list
6475;      ;; FIXME: Do we want to do this at all?
6476;      nil)
6477     ;; Everywhere else we try a function.
6478     (t
6479      (setq cw 'function)
6480      (save-excursion
6481	(if (re-search-backward "->[ \t]*\\(\\$[ \t]*\\(;.*\\)?\n\\s-*\\)?\\(\\([$a-zA-Z0-9_]+\\)::\\)?[$a-zA-Z0-9_]*\\=" bos t)
6482	    (setq cw-arrow (copy-marker (match-beginning 0))
6483		  cw-class (if (match-end 4)
6484			       (idlwave-sintern-class (match-string 4))
6485			     t))))))
6486    (list (list pro pro-point pro-class pro-arrow)
6487          (list func func-point func-class func-arrow)
6488          cw
6489	  (list cw-mod cw-point cw-class cw-arrow)
6490	  last-char)))
6491
6492(defun idlwave-this-word (&optional class)
6493  ;; Grab the word around point.  CLASS is for the `skip-chars=...' functions
6494  (setq class (or class "a-zA-Z0-9$_."))
6495  (save-excursion
6496    (buffer-substring
6497     (progn (skip-chars-backward class) (point))
6498     (progn (skip-chars-forward  class) (point)))))
6499
6500(defun idlwave-what-function (&optional bound)
6501  ;; Find out if point is within the argument list of a function.
6502  ;; The return value is ("function-name" class arrow-start (point) level).
6503  ;; Level is 1 on the top level parentheses, higher further down.
6504
6505  ;; If the optional BOUND is an integer, bound backwards directed
6506  ;;    searches to this point.
6507
6508  (catch 'exit
6509    (let (pos
6510	  func-point
6511	  (cnt 0)
6512	  func arrow-start class)
6513      (idlwave-with-special-syntax
6514       (save-restriction
6515	 (save-excursion
6516	   (narrow-to-region (max 1 (or bound 0)) (point-max))
6517	   ;; move back out of the current parenthesis
6518	   (while (condition-case nil
6519		      (progn (up-list -1) t)
6520		    (error nil))
6521	     (setq pos (point))
6522	     (cl-incf cnt)
6523	     (when (and (= (following-char) ?\()
6524			(re-search-backward
6525			 "\\(::\\|\\<\\)\\([a-zA-Z][a-zA-Z0-9$_]*\\)[ \t]*\\="
6526			 bound t))
6527	       (setq func (match-string 2)
6528		     func-point (goto-char (match-beginning 2))
6529		     pos func-point)
6530	       (if (re-search-backward
6531		    "->[ \t]*\\(\\([a-zA-Z][a-zA-Z0-9$_]*\\)::\\)?\\=" bound t)
6532		   (setq arrow-start (copy-marker (match-beginning 0))
6533			 class (or (match-string 2) t)))
6534	       (throw
6535		'exit
6536		(list
6537		 (idlwave-sintern-routine-or-method func class)
6538		 (idlwave-sintern-class class)
6539		 arrow-start func-point cnt)))
6540	     (goto-char pos))
6541	   (throw 'exit nil)))))))
6542
6543(defun idlwave-what-procedure (&optional bound)
6544  ;; Find out if point is within the argument list of a procedure.
6545  ;; The return value is ("procedure-name" class arrow-pos (point)).
6546
6547  ;; If the optional BOUND is an integer, bound backwards directed
6548  ;;    searches to this point.
6549  (let ((pos (point)) pro-point
6550	pro class arrow-start string)
6551    (save-excursion
6552      ;;(idlwave-beginning-of-statement)
6553      (idlwave-start-of-substatement 'pre)
6554      (setq string (buffer-substring (point) pos))
6555      (if (string-match
6556	   "\\`[ \t]*\\([a-zA-Z][a-zA-Z0-9$_]*\\)[ \t]*\\(,\\|\\'\\)" string)
6557	  (setq pro (match-string 1 string)
6558		pro-point (+ (point) (match-beginning 1)))
6559	(if (and (idlwave-skip-object)
6560		 (setq string (buffer-substring (point) pos))
6561		 (string-match
6562		  "\\`[ \t]*\\(->\\)[ \t]*\\(\\([a-zA-Z][a-zA-Z0-9$_]*\\)::\\)?\\([a-zA-Z][a-zA-Z0-9$_]*\\)?[ \t]*\\(,\\|\\(\\$\\s *\\(;.*\\)?\\)?$\\)"
6563		  string))
6564	    (setq pro (if (match-beginning 4)
6565			  (match-string 4 string))
6566		  pro-point (if (match-beginning 4)
6567			        (+ (point) (match-beginning 4))
6568			pos)
6569		  arrow-start (copy-marker (+ (point) (match-beginning 1)))
6570		  class (or (match-string 3 string) t)))))
6571    (list (idlwave-sintern-routine-or-method pro class)
6572	  (idlwave-sintern-class class)
6573	  arrow-start
6574	  pro-point)))
6575
6576(defun idlwave-skip-object ()
6577  ;; If there is an object at point, move over it and return t.
6578  (let ((pos (point)))
6579    (if (catch 'exit
6580	  (save-excursion
6581	    (skip-chars-forward " 	")  ; white space
6582	    (skip-chars-forward "*")        ; de-reference
6583	    (cond
6584	     ((looking-at idlwave-identifier)
6585	      (goto-char (match-end 0)))
6586	     ((eq (following-char) ?\()
6587	      nil)
6588	     (t (throw 'exit nil)))
6589	    (catch 'endwhile
6590	      (while t
6591		(cond ((eq (following-char) ?.)
6592		       (forward-char 1)
6593		       (if (not (looking-at idlwave-identifier))
6594			   (throw 'exit nil))
6595		       (goto-char (match-end 0)))
6596		      ((memq (following-char) '(?\( ?\[))
6597		       (condition-case nil
6598			   (forward-list 1)
6599			 (error (throw 'exit nil))))
6600		      (t (throw 'endwhile t)))))
6601	    (if (looking-at "[ \t]*->")
6602		(throw 'exit (setq pos (match-beginning 0)))
6603	      (throw 'exit nil))))
6604	(goto-char pos)
6605      nil)))
6606
6607(defun idlwave-last-valid-char ()
6608  "Return the last character before point which is not white or a comment
6609and also not part of the current identifier.  Since we do this in
6610order to identify places where keywords are, we consider the initial
6611`/' of a keyword as part of the identifier.
6612This function is not general, can only be used for completion stuff."
6613  (catch 'exit
6614    (save-excursion
6615      ;; skip the current identifier
6616      (skip-chars-backward "a-zA-Z0-9_$")
6617      ;; also skip a leading slash which might be belong to the keyword
6618      (if (eq (preceding-char) ?/)
6619	  (backward-char 1))
6620      ;; FIXME: does not check if this is a valid identifier
6621      (while t
6622	(skip-chars-backward " \t")
6623	(cond
6624	 ((memq (preceding-char) '(?\; ?\$)) (throw 'exit nil))
6625	 ((eq (preceding-char) ?\n)
6626	  (beginning-of-line 0)
6627	  (if (looking-at "\\([^\n]*\\)\\$[ \t]*\\(;[^\n]*\\)?\n")
6628	      ;; continuation line
6629	      (goto-char (match-end 1))
6630	    (throw 'exit nil)))
6631	 (t (throw 'exit (preceding-char))))))))
6632
6633(defvar idlwave-complete-after-success-form nil
6634  "A form to evaluate after successful completion.")
6635(defvar idlwave-complete-after-success-form-force nil
6636  "A form to evaluate after completion selection in *Completions* buffer.")
6637(defconst idlwave-completion-mark (make-marker)
6638  "A mark pointing to the beginning of the completion string.")
6639(defvar completion-highlight-first-word-only) ;XEmacs.
6640
6641(defun idlwave-complete-in-buffer (type stype list selector prompt isa
6642					&optional prepare-display-function
6643					special-selector)
6644  "Perform TYPE completion of word before point against LIST.
6645SELECTOR is the PREDICATE argument for the completion function.  Show
6646PROMPT in echo area.  TYPE is one of the intern types, e.g., `function',
6647`procedure', `class-tag', `keyword', `sysvar'.  SPECIAL-SELECTOR is
6648used only once, for `all-completions', and can be used to, e.g.,
6649accumulate information on matching completions."
6650  (let* ((completion-ignore-case t)
6651	 beg (end (point)) slash part spart completion all-completions
6652	 dpart dcompletion)
6653
6654    (unless list
6655      (error (concat prompt ": No completions available")))
6656
6657    ;; What is already in the buffer?
6658    (save-excursion
6659      (skip-chars-backward "a-zA-Z0-9_$")
6660      (setq slash (eq (preceding-char) ?/)
6661	    beg (point)
6662	    idlwave-complete-after-success-form
6663	    (list 'idlwave-after-successful-completion
6664		  (list 'quote type) slash beg)
6665	    idlwave-complete-after-success-form-force
6666	    (list 'idlwave-after-successful-completion
6667		  (list 'quote type) slash (list 'quote 'force))))
6668
6669    ;; Try a completion
6670    (setq part (buffer-substring beg end)
6671	  dpart (downcase part)
6672	  spart (idlwave-sintern stype part)
6673	  completion (try-completion part list selector)
6674	  dcompletion (if (stringp completion) (downcase completion))
6675	  idlwave-completion-help-links nil)
6676    (cond
6677     ((null completion)
6678      ;; nothing available.
6679      (error (concat prompt ": no completion for \"%s\"") part))
6680     ((and (not (equal dpart dcompletion))
6681	   (not (eq t completion)))
6682      ;; We can add something
6683      (delete-region beg end)
6684      (insert (if (and (string= part dpart)
6685                       (or (not (string= part ""))
6686                           idlwave-complete-empty-string-as-lower-case)
6687                       (not idlwave-completion-force-default-case))
6688                  dcompletion
6689                completion))
6690      (if (eq t (try-completion completion list selector))
6691	  ;; Now this is a unique match
6692	  (idlwave-after-successful-completion type slash beg))
6693      t)
6694     ((or (eq completion t)
6695	  (and (= 1 (length (setq all-completions
6696				  (idlwave-uniquify
6697				   (all-completions part list
6698						    (or special-selector
6699							selector))))))
6700	       (equal dpart dcompletion)))
6701      ;; This is already complete
6702      (idlwave-after-successful-completion type slash beg)
6703      (message "%s is already the complete %s" part isa)
6704      nil)
6705     (t
6706      ;; We cannot add something - offer a list.
6707      (message "Making completion list...")
6708
6709      (unless idlwave-completion-help-links ; already set somewhere?
6710	(mapc (lambda (x)  ; Pass link prop through to highlight-linked
6711		(let ((link (get-text-property 0 'link (car x))))
6712		  (if link
6713		      (push (cons (car x) link)
6714			    idlwave-completion-help-links))))
6715	      list))
6716      (let* ((list all-completions)
6717	     ;; "complete" means, this is already a valid completion
6718	     (complete (memq spart all-completions))
6719	     (completion-highlight-first-word-only t)) ; XEmacs
6720	     ;; (completion-fixup-function             ; Emacs
6721	     ;;  (lambda () (and (eq (preceding-char) ?>)
6722	     ;;    	      (re-search-backward " <" beg t)))))
6723
6724	(setq list (sort list (lambda (a b)
6725				(string< (downcase a) (downcase b)))))
6726	(if prepare-display-function
6727	    (setq list (funcall prepare-display-function list)))
6728	(if (and (string= part dpart)
6729		 (or (not (string= part ""))
6730		     idlwave-complete-empty-string-as-lower-case)
6731		 (not idlwave-completion-force-default-case))
6732	    (setq list (mapcar (lambda (x)
6733				 (if (listp x)
6734				     (setcar x (downcase (car x)))
6735				   (setq x (downcase x)))
6736				 x)
6737			       list)))
6738	(idlwave-display-completion-list list prompt beg complete))
6739      t))))
6740
6741(defun idlwave-complete-class ()
6742  "Complete a class at point."
6743  (interactive)
6744  ;; Call `idlwave-routines' to make sure the class list will be available
6745  (idlwave-routines)
6746  ;; Check for the special case of completing empty string after pro/function
6747  (if (let ((case-fold-search t))
6748	(save-excursion
6749	  (and
6750	   (re-search-backward "\\<\\(pro\\|function\\)[ \t]+\\="
6751			       (- (point) 15) t)
6752	   (goto-char (point-min))
6753	   (re-search-forward
6754	    "^[ \t]*\\(pro\\|function\\)[ \t]+\\([a-zA-Z0-9_]+::\\)" nil t))))
6755      ;; Yank the full class specification
6756      (insert (match-string 2))
6757    ;; Do the completion, using list gathered from `idlwave-routines'
6758    (idlwave-complete-in-buffer
6759     'class 'class (idlwave-class-alist) nil
6760     "Select a class" "class"
6761     (lambda (list) ;; Push it to help-links if system help available
6762       (mapcar (lambda (x)
6763                 (let* ((entry (idlwave-class-info x))
6764                        (link (nth 1 (assq 'link entry))))
6765                   (if link (push (cons x link)
6766                                  idlwave-completion-help-links))
6767                   x))
6768               list)))))
6769
6770(defun idlwave-attach-classes (list type show-classes)
6771  ;; Attach the proper class list to a LIST of completion items.
6772  ;; TYPE, when 'kwd, shows classes for method keywords, when
6773  ;; 'class-tag, for class tags, and otherwise for methods.
6774  ;; SHOW-CLASSES is the value of `idlwave-completion-show-classes'.
6775  (if (or (null show-classes)           ; don't want to see classes
6776	  (null class-selector)         ; not a method call
6777	  (and
6778	   (stringp class-selector) ; the class is already known
6779	   (not super-classes)))    ; no possibilities for inheritance
6780      ;; In these cases, we do not have to do anything
6781      list
6782    (let* ((do-prop (and (>= show-classes 0)
6783			 (>= emacs-major-version 21)))
6784	   (do-buf (not (= show-classes 0)))
6785	   ;; (do-dots (featurep 'xemacs))
6786	   (do-dots t)
6787	   (inherit (if (and (not (eq type 'class-tag)) super-classes)
6788			(cons class-selector super-classes)))
6789	   (max (abs show-classes))
6790	   (lmax (if do-dots (apply 'max (mapcar 'length list))))
6791	  classes nclasses class-info space)
6792      (mapcar
6793       (lambda (x)
6794	 ;; get the classes
6795	 (if (eq type 'class-tag)
6796	     ;; Just one class for tags
6797	     (setq classes
6798		   (list
6799		    (idlwave-class-or-superclass-with-tag class-selector x)))
6800	   ;; Multiple classes for method or method-keyword
6801	   (setq classes
6802		 (if (eq type 'kwd)
6803		     (idlwave-all-method-keyword-classes
6804		      method-selector x type-selector)
6805		   (idlwave-all-method-classes x type-selector)))
6806	   (if inherit
6807	       (setq classes
6808		     (delq nil
6809			   (mapcar (lambda (x) (if (memq x inherit) x nil))
6810				   classes)))))
6811	 (setq nclasses (length classes))
6812	 ;; Make the separator between item and class-info
6813	 (if do-dots
6814	     (setq space (concat " " (make-string (- lmax (length x)) ?.)))
6815	   (setq space " "))
6816	 (if  do-buf
6817	     ;; We do want info in the buffer
6818	     (if (<= nclasses max)
6819		 (setq class-info (concat
6820				   space
6821				   "<" (mapconcat 'identity classes ",") ">"))
6822	       (setq class-info (format "%s<%d classes>" space nclasses)))
6823	   (setq class-info nil))
6824	 (when do-prop
6825	   ;; We do want properties
6826	   (setq x (copy-sequence x))
6827	   (put-text-property 0 (length x)
6828                              'help-echo (mapconcat 'identity classes " ")
6829                              x))
6830	 (if class-info
6831	     (list x class-info)
6832	   x))
6833       list))))
6834
6835(defun idlwave-attach-method-classes (list)
6836  ;; Call idlwave-attach-classes with method parameters
6837  (idlwave-attach-classes list 'method idlwave-completion-show-classes))
6838(defun idlwave-attach-keyword-classes (list)
6839  ;; Call idlwave-attach-classes with keyword parameters
6840  (idlwave-attach-classes list 'kwd idlwave-completion-show-classes))
6841(defun idlwave-attach-class-tag-classes (list)
6842  ;; Call idlwave-attach-classes with class structure tags
6843  (idlwave-attach-classes list 'class-tag idlwave-completion-show-classes))
6844
6845
6846;;----------------------------------------------------------------------
6847;;----------------------------------------------------------------------
6848;;----------------------------------------------------------------------
6849;;----------------------------------------------------------------------
6850;;----------------------------------------------------------------------
6851(when (featurep 'xemacs)
6852  (defvar rtn)
6853  (defun idlwave-pset (item)
6854    (set 'rtn item)))
6855
6856(defun idlwave-popup-select (ev list title &optional sort)
6857  "Select an item in LIST with a popup menu.
6858TITLE is the title to put atop the popup.  If SORT is non-nil,
6859sort the list before displaying."
6860  (let ((maxpopup idlwave-max-popup-menu-items)
6861	rtn menu)
6862    (cond ((null list))
6863	  ((= 1 (length list))
6864	   (setq rtn (car list)))
6865	  ((featurep 'xemacs)
6866	   (if sort (setq list (sort list (lambda (a b)
6867					    (string< (upcase a) (upcase b))))))
6868	   (setq menu
6869		 (append (list title)
6870			 (mapcar (lambda (x) (vector x (list 'idlwave-pset
6871							     x)))
6872				 list)))
6873	   (setq menu (idlwave-split-menu-xemacs menu maxpopup))
6874	   (let ((resp (get-popup-menu-response menu)))
6875             (funcall (event-function resp) (event-object resp))))
6876	  (t
6877	   (if sort (setq list (sort list (lambda (a b)
6878					    (string< (upcase a) (upcase b))))))
6879	   (setq menu (cons title
6880			    (list
6881			     (append (list "")
6882				     (mapcar (lambda(x) (cons x x)) list)))))
6883	   (setq menu (idlwave-split-menu-emacs menu maxpopup))
6884	   (setq rtn (x-popup-menu ev menu))))
6885    rtn))
6886
6887(defun idlwave-split-menu-xemacs (menu N)
6888  "Split the MENU into submenus of maximum length N."
6889  (if (<= (length menu) (1+ N))
6890      ;; No splitting needed
6891      menu
6892    (let* ((title (car menu))
6893	   (entries (cdr menu))
6894	   (menu (list title))
6895	   (cnt 0)
6896	   (nextmenu nil))
6897      (while entries
6898	(while (and entries (< cnt N))
6899	  (setq cnt (1+ cnt)
6900		nextmenu (cons (car entries) nextmenu)
6901		entries (cdr entries)))
6902	(setq nextmenu (nreverse nextmenu))
6903	(setq nextmenu (cons (format "%s...%s"
6904				     (aref (car nextmenu) 0)
6905				     (aref (nth (1- cnt) nextmenu) 0))
6906			     nextmenu))
6907	(setq menu (cons nextmenu menu)
6908	      nextmenu nil
6909	      cnt 0))
6910      (nreverse menu))))
6911
6912(defun idlwave-split-menu-emacs (menu N)
6913  "Split the MENU into submenus of maximum length N."
6914  (if (<= (length (nth 1 menu)) (1+ N))
6915      ;; No splitting needed
6916      menu
6917    (let* ((title (car menu))
6918	   (entries (cdr (nth 1 menu)))
6919	   (menu nil)
6920	   (cnt 0)
6921	   (nextmenu nil))
6922      (while entries
6923	(while (and entries (< cnt N))
6924	  (setq cnt (1+ cnt)
6925		nextmenu (cons (car entries) nextmenu)
6926		entries (cdr entries)))
6927	(setq nextmenu (nreverse nextmenu))
6928	(prin1 nextmenu)
6929	(setq nextmenu (cons (format "%s...%s"
6930				     (car (car nextmenu))
6931				     (car (nth (1- cnt) nextmenu)))
6932			     nextmenu))
6933	(setq menu (cons nextmenu menu)
6934	      nextmenu nil
6935	      cnt 0))
6936      (setq menu (nreverse menu))
6937      (setq menu (cons title menu))
6938      menu)))
6939
6940(defvar idlwave-completion-setup-hook nil)
6941
6942(defun idlwave-scroll-completions (&optional message)
6943  "Scroll the completion window on this frame."
6944  (let ((cwin (get-buffer-window "*Completions*" 'visible))
6945	(win (selected-window)))
6946    (unwind-protect
6947	(progn
6948	  (select-window cwin)
6949	  (condition-case nil
6950	      (scroll-up)
6951	    (error (if (and (listp last-command)
6952			    (nth 2 last-command))
6953		       (progn
6954			 (select-window win)
6955			 (eval idlwave-complete-after-success-form))
6956		     (set-window-start cwin (point-min)))))
6957	  (and message (message "%s" message)))
6958      (select-window win))))
6959
6960(defun idlwave-display-completion-list (list &optional message beg complete)
6961  "Display the completions in LIST in the completions buffer and echo MESSAGE."
6962  (unless (and (get-buffer-window "*Completions*")
6963	       (idlwave-local-value 'idlwave-completion-p "*Completions*"))
6964    (move-marker idlwave-completion-mark beg)
6965    (setq idlwave-before-completion-wconf (current-window-configuration)))
6966
6967  (if (featurep 'xemacs)
6968      (idlwave-display-completion-list-xemacs
6969       list)
6970    (idlwave-display-completion-list-emacs list))
6971
6972  ;; Store a special value in `this-command'.  When `idlwave-complete'
6973  ;; finds this in `last-command', it will scroll the *Completions* buffer.
6974  (setq this-command (list 'idlwave-display-completion-list message complete))
6975
6976  ;; Mark the completions buffer as created by cib
6977  (idlwave-set-local 'idlwave-completion-p t "*Completions*")
6978
6979  ;; Fontify the classes
6980  (if (and idlwave-completion-fontify-classes
6981           (consp (car list)))
6982      (idlwave-completion-fontify-classes))
6983
6984  ;; Run the hook
6985  (run-hooks 'idlwave-completion-setup-hook)
6986
6987  ;; Display the message
6988  (message "%s" (or message "Making completion list...done")))
6989
6990(defun idlwave-choose (function &rest args)
6991  "Call FUNCTION as a completion chooser and pass ARGS to it."
6992  (let ((completion-ignore-case t))	    ; install correct value
6993    (apply function args))
6994  (if (and (derived-mode-p 'idlwave-shell-mode)
6995	   (boundp 'font-lock-mode)
6996	   (not font-lock-mode))
6997      ;; For the shell, remove the fontification of the word before point
6998      (let ((beg (save-excursion
6999		   (skip-chars-backward "a-zA-Z0-9_")
7000		   (point))))
7001	(remove-text-properties beg (point) '(face nil))))
7002  (eval idlwave-complete-after-success-form-force))
7003
7004(defun idlwave-keyboard-quit ()
7005  (interactive)
7006  (unwind-protect
7007      (if (eq (car-safe last-command) 'idlwave-display-completion-list)
7008	  (idlwave-restore-wconf-after-completion))
7009    (keyboard-quit)))
7010
7011(defun idlwave-restore-wconf-after-completion ()
7012  "Restore the old (before completion) window configuration."
7013  (and idlwave-completion-restore-window-configuration
7014       idlwave-before-completion-wconf
7015       (set-window-configuration idlwave-before-completion-wconf)))
7016
7017(defun idlwave-one-key-select (sym prompt delay)
7018  "Make the user select an element from the alist in the variable SYM.
7019The keys of the alist are expected to be strings.  The function returns the
7020car of the selected association.
7021To do this, PROMPT is displayed and the user must hit a letter key to
7022select an entry.  If the user does not reply within DELAY seconds, a help
7023window with the options is displayed automatically.
7024The key which is associated with each option is generated automatically.
7025First, the strings are checked for preselected keys, like in \"[P]rint\".
7026If these don't exist, a letter in the string is automatically selected."
7027  (let* ((alist (symbol-value sym))
7028         (temp-buffer-show-hook (if (fboundp 'fit-window-to-buffer)
7029				    '(fit-window-to-buffer)))
7030         keys-alist char)
7031    ;; First check the cache
7032    (if (and (eq (symbol-value sym) (get sym :one-key-alist-last)))
7033        (setq keys-alist (get sym :one-key-alist-cache))
7034      ;; Need to make new list
7035      (setq keys-alist (idlwave-make-one-key-alist alist))
7036      (put sym :one-key-alist-cache keys-alist)
7037      (put sym :one-key-alist-last alist))
7038    ;; Display prompt and wait for quick reply
7039    (message "%s[%s]" prompt
7040             (mapconcat (lambda(x) (char-to-string (car x)))
7041                        keys-alist ""))
7042    (if (sit-for delay)
7043        ;; No quick reply: Show help
7044        (save-window-excursion
7045          (with-output-to-temp-buffer "*Completions*"
7046	    (dolist (x keys-alist)
7047	      (princ (nth 1 x))
7048	      (princ "\n")))
7049          (setq char (read-char)))
7050      (setq char (read-char)))
7051    (message nil)
7052    ;; Return the selected result
7053    (nth 2 (assoc char keys-alist))))
7054
7055;; Used for, e.g., electric debug super-examine.
7056(defun idlwave-make-one-key-alist (alist)
7057  "Make an alist for single key selection."
7058  (let ((l alist) keys-alist name start char help
7059        (cnt 0)
7060        (case-fold-search nil))
7061    (while l
7062      (setq name (car (car l))
7063            l (cdr l))
7064      (catch 'exit
7065        ;; First check if the configuration predetermined a key
7066        (if (string-match "\\[\\(.\\)\\]" name)
7067            (progn
7068              (setq char (string-to-char (downcase (match-string 1 name)))
7069                    help (format "%c:  %s" char name)
7070                    keys-alist (cons (list char help name) keys-alist))
7071              (throw 'exit t)))
7072        ;; Then check for capital letters
7073        (setq start 0)
7074        (while (string-match "[A-Z]" name start)
7075          (setq start (match-end 0)
7076                char (string-to-char (downcase (match-string 0 name))))
7077          (if (not (assoc char keys-alist))
7078              (progn
7079                (setq help (format "%c:  %s" char
7080                                   (replace-match
7081                                    (concat "[" (match-string 0 name) "]")
7082                                          t t name))
7083                      keys-alist (cons (list char help name) keys-alist))
7084                (throw 'exit t))))
7085        ;; Now check for lowercase letters
7086        (setq start 0)
7087        (while (string-match "[a-z]" name start)
7088          (setq start (match-end 0)
7089                char (string-to-char (match-string 0 name)))
7090          (if (not (assoc char keys-alist))
7091              (progn
7092                (setq help (format "%c:  %s" char
7093                                   (replace-match
7094                                    (concat "[" (match-string 0 name) "]")
7095                                    t t name))
7096                      keys-alist (cons (list char help name) keys-alist))
7097                (throw 'exit t))))
7098        ;; Bummer, nothing found!  Use a stupid number
7099        (setq char (string-to-char (int-to-string (setq cnt (1+ cnt))))
7100              help (format "%c:  %s" char name)
7101              keys-alist (cons (list char help name) keys-alist))))
7102    (nreverse keys-alist)))
7103
7104(defun idlwave-set-local (var value &optional buffer)
7105  "Set the buffer-local value of VAR in BUFFER to VALUE."
7106  (with-current-buffer (or buffer (current-buffer))
7107    (set (make-local-variable var) value)))
7108
7109(defun idlwave-local-value (var &optional buffer)
7110  "Return the value of VAR in BUFFER, but only if VAR is local to BUFFER."
7111  (with-current-buffer (or buffer (current-buffer))
7112    (and (local-variable-p var (current-buffer))
7113	 (symbol-value var))))
7114
7115;; In XEmacs, we can use :activate-callback directly to advice the
7116;; choose functions.  We use the private keymap only for the online
7117;; help feature.
7118
7119(defvar idlwave-completion-map nil
7120  "Keymap for `completion-list-mode' with `idlwave-complete'.")
7121
7122(defun idlwave-display-completion-list-xemacs (list &rest cl-args)
7123  (with-output-to-temp-buffer "*Completions*"
7124    (apply 'display-completion-list list
7125	   ':activate-callback 'idlwave-default-choose-completion
7126	   cl-args))
7127  (with-current-buffer "*Completions*"
7128    (use-local-map
7129     (or idlwave-completion-map
7130	 (setq idlwave-completion-map
7131	       (idlwave-make-modified-completion-map-xemacs
7132		(current-local-map)))))))
7133
7134(defun idlwave-default-choose-completion (&rest args)
7135  "Execute `default-choose-completion' and then restore the win-conf."
7136  (apply 'idlwave-choose 'default-choose-completion args))
7137
7138(defun idlwave-make-modified-completion-map-xemacs (old-map)
7139  "Replace `choose-completion' and `mouse-choose-completion' in OLD-MAP."
7140  (let ((new-map (copy-keymap old-map)))
7141    (define-key new-map [button3up] 'idlwave-mouse-completion-help)
7142    (define-key new-map [button3] (lambda ()
7143				    (interactive)
7144				    (setq this-command last-command)))
7145    new-map))
7146
7147;; In Emacs we also replace keybindings in the completion
7148;; map in order to install our wrappers.
7149
7150(defun idlwave-display-completion-list-emacs (list)
7151  "Display completion list and install the choose wrappers."
7152  (with-output-to-temp-buffer "*Completions*"
7153    (display-completion-list list))
7154  (with-current-buffer "*Completions*"
7155    (use-local-map
7156     (or idlwave-completion-map
7157	 (setq idlwave-completion-map
7158	       (idlwave-make-modified-completion-map-emacs
7159		(current-local-map)))))))
7160
7161(defun idlwave-make-modified-completion-map-emacs (old-map)
7162  "Replace `choose-completion' and `mouse-choose-completion' in OLD-MAP."
7163  (let ((new-map (copy-keymap old-map)))
7164    (substitute-key-definition
7165     'choose-completion 'idlwave-choose-completion new-map)
7166    (substitute-key-definition
7167     'mouse-choose-completion 'idlwave-mouse-choose-completion new-map)
7168    (define-key new-map [mouse-3] 'idlwave-mouse-completion-help)
7169    new-map))
7170
7171(defun idlwave-choose-completion (&rest args)
7172  "Choose the completion that point is in or next to."
7173  (interactive (list last-nonmenu-event))
7174  (apply 'idlwave-choose 'choose-completion args))
7175
7176(defun idlwave-mouse-choose-completion (&rest args)
7177  "Click on an alternative in the `*Completions*' buffer to choose it."
7178  (interactive "e")
7179  (apply 'idlwave-choose 'mouse-choose-completion args))
7180
7181;;----------------------------------------------------------------------
7182;;----------------------------------------------------------------------
7183
7184;;; ------------------------------------------------------------------------
7185;;; Structure parsing code, and code to manage class info
7186
7187;;
7188;; - Go again over the documentation how to write a completion
7189;;   plugin.  It is in self.el, but currently still very bad.
7190;;   This could be in a separate file in the distribution, or
7191;;   in an appendix for the manual.
7192
7193(defvar idlwave-struct-skip
7194  "[ \t]*\\(\\$.*\n\\(^[ \t]*\\(\\$[ \t]*\\)?\\(;.*\\)?\n\\)*\\)?[ \t]*"
7195  "Regexp for skipping continued blank or comment-only lines in structures.")
7196
7197(defvar idlwave-struct-tag-regexp
7198  (concat "[{,]" ;leading comma/brace
7199	  idlwave-struct-skip ; 4 groups
7200	  "\\([a-zA-Z][a-zA-Z0-9_]*\\)" ;the tag itself, group 5
7201	  "[ \t]*:") ; the final colon
7202  "Regexp for structure tags.")
7203
7204(defun idlwave-struct-tags ()
7205  "Return a list of all tags in the structure defined at point.
7206Point is expected just before the opening `{' of the struct definition."
7207  (save-excursion
7208    (let* ((borders (idlwave-struct-borders))
7209	   (beg (car borders))
7210	   (end (cdr borders))
7211	   tags)
7212      (goto-char beg)
7213      (save-restriction
7214	(narrow-to-region beg end)
7215	(while (re-search-forward idlwave-struct-tag-regexp end t)
7216	  ;; Check if we are still on the top level of the structure.
7217	  (if (and (condition-case nil (progn (up-list -1) t) (error nil))
7218		   (= (point) beg))
7219	      (push (match-string-no-properties 5) tags))
7220	  (goto-char (match-end 0))))
7221	(nreverse tags))))
7222
7223(defun idlwave-find-struct-tag (tag)
7224  "Find a given TAG in the structure defined at point."
7225  (let* ((borders (idlwave-struct-borders))
7226	 (end (cdr borders))
7227	 (case-fold-search t))
7228    (re-search-forward (concat "\\(^[ \t]*\\|[,{][ \t]*\\)" tag "[ \t]*:")
7229		       end t)))
7230
7231(defun idlwave-struct-inherits ()
7232  "Return a list of all `inherits' names in the struct at point.
7233Point is expected just before the opening `{' of the struct definition."
7234  (save-excursion
7235    (let* ((borders (idlwave-struct-borders))
7236	   (beg (car borders))
7237	   (end (cdr borders))
7238	   (case-fold-search t)
7239	   names)
7240      (goto-char beg)
7241      (save-restriction
7242	(narrow-to-region beg end)
7243	(while (re-search-forward
7244		(concat "[{,]"  ;leading comma/brace
7245			idlwave-struct-skip ; 4 groups
7246			"inherits"    ; The INHERITS tag
7247			idlwave-struct-skip ; 4 more
7248			"\\([a-zA-Z][a-zA-Z0-9_]*\\)") ; The super-group, #9
7249		end t)
7250	  ;; Check if we are still on the top level of the structure.
7251	  (if (and (condition-case nil (progn (up-list -1) t) (error nil))
7252		   (= (point) beg))
7253	      (push (match-string-no-properties 9) names))
7254	  (goto-char (match-end 0))))
7255      (nreverse names))))
7256
7257(defun idlwave-in-structure ()
7258  "Return t if point is inside an IDL structure definition."
7259  (let ((beg (point)))
7260    (save-excursion
7261      (if (not (or (idlwave-in-comment) (idlwave-in-quote)))
7262	  (if (idlwave-find-structure-definition nil nil 'back)
7263	      (let ((borders (idlwave-struct-borders)))
7264		(or (= (car borders) (cdr borders)) ;; struct not yet closed...
7265		    (and (> beg (car borders)) (< beg (cdr borders))))))))))
7266
7267(defun idlwave-struct-borders ()
7268  "Return the borders of the {...} after point as a cons cell."
7269  (let (beg)
7270    (save-excursion
7271      (skip-chars-forward "^{")
7272      (setq beg (point))
7273      (condition-case nil (forward-list 1)
7274	(error (goto-char beg)))
7275      (cons beg (point)))))
7276
7277(defun idlwave-find-structure-definition (&optional var name bound)
7278  "Search forward for a structure definition.
7279If VAR is non-nil, search for a structure assigned to variable VAR.
7280If NAME is non-nil, search for a named structure NAME, if a string,
7281or a generic named structure otherwise.  If BOUND is an integer, limit
7282the search.  If BOUND is the symbol `all', we search first back and
7283then forward through the entire file.  If BOUND is the symbol `back'
7284we search only backward."
7285  (let* ((ws "[ \t]*\\(\\$.*\n[ \t]*\\)*")
7286	 (case-fold-search t)
7287	 (lim (if (integerp bound) bound nil))
7288	 (re (concat
7289	      (if var
7290		  (concat "\\<" (regexp-quote (downcase var)) "\\>" ws)
7291		"\\(\\)")
7292	      "=" ws "\\({\\)"
7293	      (if name
7294		  (if (stringp name)
7295		      (concat ws "\\(\\<" (downcase name) "\\)[^a-zA-Z0-9_$]")
7296		    ;; Just a generic name
7297		    (concat ws "\\<\\([a-zA-Z_0-9$]+\\)" ws ","))
7298		""))))
7299    (if (or (and (or (eq bound 'all) (eq bound 'back))
7300		 (re-search-backward re nil t))
7301	    (and (not (eq bound 'back)) (re-search-forward re lim t)))
7302	(progn
7303	  (goto-char (match-beginning 3))
7304	  (match-string-no-properties 5)))))
7305
7306(defvar idlwave-class-info nil)
7307(defvar idlwave-class-reset nil) ; to reset buffer-local classes
7308
7309(add-hook 'idlwave-update-rinfo-hook
7310	  (lambda () (setq idlwave-class-reset t)))
7311(add-hook 'idlwave-after-load-rinfo-hook
7312	  (lambda () (setq idlwave-class-info nil)))
7313
7314(defun idlwave-class-info (class)
7315  (let (list entry)
7316    (if idlwave-class-info
7317	(if idlwave-class-reset
7318	    (setq
7319	     idlwave-class-reset nil
7320	     idlwave-class-info ; Remove any visited in a buffer
7321	     (delq nil (mapcar
7322			(lambda (x)
7323			  (let ((filebuf
7324				 (idlwave-class-file-or-buffer
7325				  (or (cdr (assq 'found-in x)) (car x)))))
7326			    (if (cdr filebuf)
7327				nil
7328			      x)))
7329			idlwave-class-info))))
7330      ;; Info is nil, put in the system stuff to start.
7331      (setq idlwave-class-info idlwave-system-class-info)
7332      (setq list idlwave-class-info)
7333      (while (setq entry (pop list))
7334	(idlwave-sintern-class-info entry)))
7335    (setq class (idlwave-sintern-class class))
7336    (or (assq class idlwave-class-info)
7337	(progn (idlwave-scan-class-info class)
7338	       (assq class idlwave-class-info)))))
7339
7340(defun idlwave-sintern-class-info (entry)
7341  "Sintern the class names in a class-info entry."
7342  (let ((inherits (assq 'inherits entry)))
7343    (setcar entry (idlwave-sintern-class (car entry) 'set))
7344    (if inherits
7345	(setcdr inherits (mapcar (lambda (x) (idlwave-sintern-class x 'set))
7346				 (cdr inherits))))))
7347
7348(defun idlwave-find-class-definition (class &optional all-hook alt-class)
7349  "Find class structure definition(s).
7350If ALL-HOOK is set, find all named structure definitions in a given
7351class__define routine, on which ALL-HOOK will be run.  If ALT-CLASS is
7352set, look for the name__define pro, and inside of it, for the ALT-CLASS
7353class/struct definition."
7354  (let ((case-fold-search t) end-lim name)
7355    (when (re-search-forward
7356	   (concat "^[ \t]*pro[ \t]+" (downcase class) "__define" "\\>") nil t)
7357      (if all-hook
7358	  (progn
7359	    ;; For everything there
7360	    (setq end-lim (save-excursion (idlwave-end-of-subprogram) (point)))
7361	    (while (setq name
7362			 (idlwave-find-structure-definition nil t end-lim))
7363	      (funcall all-hook name)))
7364	(idlwave-find-structure-definition nil (or alt-class class))))))
7365
7366
7367(defun idlwave-class-file-or-buffer (class)
7368  "Find buffer visiting CLASS definition."
7369  (let* ((pro (concat (downcase class) "__define"))
7370	 (file (idlwave-routine-source-file
7371		(nth 3 (idlwave-rinfo-assoc pro 'pro nil
7372					    (idlwave-routines))))))
7373    (cons file (if file (idlwave-get-buffer-visiting file)))))
7374
7375
7376(defun idlwave-scan-class-info (class)
7377  "Scan all class and named structure info in the class__define pro."
7378  (let* ((idlwave-auto-routine-info-updates nil)
7379	 (filebuf (idlwave-class-file-or-buffer class))
7380	 (file (car filebuf))
7381	 (buf (cdr filebuf))
7382	 (class (idlwave-sintern-class class)))
7383    (if (or
7384	 (not file)
7385	 (and ;; neither a regular file nor a visited buffer
7386	  (not buf)
7387	  (not (file-regular-p file))))
7388	nil ; Cannot find the file/buffer to get any info
7389      (save-excursion
7390	(if buf (set-buffer buf)
7391	  ;; Read the file in temporarily
7392	  (set-buffer (get-buffer-create " *IDLWAVE-tmp*"))
7393	  (erase-buffer)
7394	  (unless (derived-mode-p 'idlwave-mode)
7395	    (idlwave-mode))
7396	  (insert-file-contents file))
7397	(save-excursion
7398	  (goto-char 1)
7399	  (idlwave-find-class-definition class
7400	   ;; Scan all of the structures found there
7401	   (lambda (name)
7402	     (let* ((this-class (idlwave-sintern-class name))
7403		    (entry
7404		     (list this-class
7405			   (cons 'tags (idlwave-struct-tags))
7406			   (cons 'inherits (idlwave-struct-inherits)))))
7407	       (if (not (eq this-class class))
7408		   (setq entry (nconc entry (list (cons 'found-in class)))))
7409	       (idlwave-sintern-class-info entry)
7410	       (push entry idlwave-class-info)))))))))
7411
7412(defun idlwave-class-found-in (class)
7413  "Return the FOUND-IN property of the CLASS."
7414  (cdr (assq 'found-in (idlwave-class-info class))))
7415(defun idlwave-class-tags (class)
7416  "Return the native tags in CLASS."
7417  (cdr (assq 'tags (idlwave-class-info class))))
7418(defun idlwave-class-inherits (class)
7419  "Return the direct superclasses of CLASS."
7420  (cdr (assq 'inherits (idlwave-class-info class))))
7421
7422
7423(defun idlwave-all-class-tags (class)
7424  "Return a list of native and inherited tags in CLASS."
7425  (condition-case err
7426      (apply 'append (mapcar 'idlwave-class-tags
7427			     (cons class (idlwave-all-class-inherits class))))
7428    (error
7429     (idlwave-class-tag-reset)
7430     (error "%s" (error-message-string err)))))
7431
7432
7433(defun idlwave-all-class-inherits (class)
7434  "Return a list of all superclasses of CLASS (recursively expanded).
7435The list is cached in `idlwave-class-info' for faster access."
7436  (cond
7437   ((not idlwave-support-inheritance) nil)
7438   ((eq class nil) nil)
7439   ((eq class t) nil)
7440   (t
7441    (let ((info (idlwave-class-info class))
7442	  entry)
7443      (if (setq entry (assq 'all-inherits info))
7444	  (cdr entry)
7445	;; Save the depth of inheritance scan to check for circular references
7446	(let ((inherits (mapcar (lambda (x) (cons x 0))
7447				(idlwave-class-inherits class)))
7448	      rtn all-inherits cl)
7449	  (while inherits
7450	    (setq cl (pop inherits)
7451		  rtn (cons (car cl) rtn)
7452		  inherits (append (mapcar (lambda (x)
7453					     (cons x (1+ (cdr cl))))
7454					   (idlwave-class-inherits (car cl)))
7455				   inherits))
7456	    (if (> (cdr cl) 999)
7457	      (error
7458	       "Class scan: inheritance depth exceeded. Circular inheritance?")
7459	      ))
7460	  (setq all-inherits (nreverse rtn))
7461	  (nconc info (list (cons 'all-inherits all-inherits)))
7462	  all-inherits))))))
7463
7464(defun idlwave-entry-keywords (entry &optional record-link)
7465  "Return the flat entry keywords alist from routine-info entry.
7466If RECORD-LINK is non-nil, the keyword text is copied and a text
7467property indicating the link is added."
7468  (let (kwds)
7469    (mapc
7470     (lambda (key-list)
7471       (let ((file (car key-list)))
7472	 (mapcar (lambda (key-cons)
7473		   (let ((key (car key-cons))
7474			 (link (cdr key-cons)))
7475		     (when (and record-link file)
7476			 (setq key (copy-sequence key))
7477			 (put-text-property
7478			  0 (length key)
7479			  'link
7480			  (concat
7481			   file
7482			   (if link
7483			       (concat idlwave-html-link-sep
7484				       (number-to-string link))))
7485			  key))
7486		     (push (list key) kwds)))
7487		 (cdr key-list))))
7488     (nthcdr 5 entry))
7489    (nreverse kwds)))
7490
7491(defun idlwave-entry-find-keyword (entry keyword)
7492  "Find keyword KEYWORD in entry ENTRY, and return (with link) if set."
7493  (catch 'exit
7494    (mapc
7495     (lambda (key-list)
7496       (let ((file (car key-list))
7497	     (kwd (assoc keyword (cdr key-list))))
7498	 (when kwd
7499	   (setq kwd (cons (car kwd)
7500			   (if (and file (cdr kwd))
7501			       (concat file
7502				       idlwave-html-link-sep
7503				       (number-to-string (cdr kwd)))
7504			     (cdr kwd))))
7505	   (throw 'exit kwd))))
7506     (nthcdr 5 entry))))
7507
7508;;==========================================================================
7509;;
7510;; Completing class structure tags.  This is a completion plugin.
7511;; The necessary taglist is constructed dynamically
7512
7513(defvar idlwave-current-tags-class nil)
7514(defvar idlwave-current-class-tags nil)
7515(defvar idlwave-current-native-class-tags nil)
7516(defvar idlwave-sint-class-tags nil)
7517(declare-function idlwave-sintern-class-tag "idlwave" t t)
7518(idlwave-new-sintern-type 'class-tag)
7519(add-to-list 'idlwave-complete-special 'idlwave-complete-class-structure-tag)
7520(add-hook 'idlwave-update-rinfo-hook 'idlwave-class-tag-reset)
7521
7522(defun idlwave-complete-class-structure-tag ()
7523  "Complete a structure tag on a `self' argument in an object method."
7524  (interactive)
7525  (let ((pos (point))
7526	(case-fold-search t))
7527    (if (save-excursion
7528	  ;; Check if the context is right
7529	  (skip-chars-backward "a-zA-Z0-9._$")
7530	  (and (< (point) (- pos 4))
7531	       (looking-at "self\\.")))
7532	(let* ((class-selector (nth 2 (idlwave-current-routine)))
7533	       (super-classes (idlwave-all-class-inherits class-selector)))
7534	  ;; Check if we are in a class routine
7535	  (unless class-selector
7536	    (error "Not in a method procedure or function"))
7537	  ;; Check if we need to update the "current" class
7538	  (if (not (equal class-selector idlwave-current-tags-class))
7539	      (idlwave-prepare-class-tag-completion class-selector))
7540	  (setq idlwave-completion-help-info
7541		(list 'idlwave-complete-class-structure-tag-help
7542		      (idlwave-sintern-routine
7543		       (concat class-selector "__define"))
7544		      nil))
7545          ;; FIXME: idlwave-cpl-bold doesn't seem used anywhere.
7546	  (let  ((idlwave-cpl-bold idlwave-current-native-class-tags))
7547	    (idlwave-complete-in-buffer
7548	     'class-tag 'class-tag
7549	     idlwave-current-class-tags nil
7550	     (format "Select a tag of class %s" class-selector)
7551	     "class tag"
7552	     'idlwave-attach-class-tag-classes))
7553	  t) ; return t to skip other completions
7554      nil)))
7555
7556(defun idlwave-class-tag-reset ()
7557  (setq idlwave-current-tags-class nil))
7558
7559(defun idlwave-prepare-class-tag-completion (class)
7560  "Find and parse the necessary class definitions for class structure tags."
7561  (setq idlwave-sint-class-tags nil)
7562  (setq idlwave-current-tags-class class)
7563  (setq idlwave-current-class-tags
7564	(mapcar (lambda (x)
7565		  (list (idlwave-sintern-class-tag x 'set)))
7566		(idlwave-all-class-tags class)))
7567  (setq idlwave-current-native-class-tags
7568	(mapcar 'downcase (idlwave-class-tags class))))
7569
7570;===========================================================================
7571;;
7572;; Completing system variables and their structure fields
7573;; This is also a plugin.
7574
7575(defvar idlwave-sint-sysvars nil)
7576(defvar idlwave-sint-sysvartags nil)
7577(declare-function idlwave-sintern-sysvar    "idlwave" t t)
7578(declare-function idlwave-sintern-sysvartag "idlwave" t t)
7579(idlwave-new-sintern-type 'sysvar)
7580(idlwave-new-sintern-type 'sysvartag)
7581(add-to-list 'idlwave-complete-special 'idlwave-complete-sysvar-or-tag)
7582(add-hook 'idlwave-update-rinfo-hook 'idlwave-sysvars-reset)
7583(add-hook 'idlwave-after-load-rinfo-hook 'idlwave-sintern-sysvar-alist)
7584
7585
7586(defun idlwave-complete-sysvar-or-tag ()
7587  "Complete a system variable."
7588  (interactive)
7589  (let ((pos (point))
7590	(case-fold-search t))
7591    (cond ((save-excursion
7592	     ;; Check if the context is right for system variable
7593	     (skip-chars-backward "a-zA-Z0-9_$")
7594	     (equal (char-before) ?!))
7595	   (setq idlwave-completion-help-info '(idlwave-complete-sysvar-help))
7596	   (idlwave-complete-in-buffer 'sysvar 'sysvar
7597				       idlwave-system-variables-alist nil
7598				       "Select a system variable"
7599				       "system variable")
7600	   t)  ; return t to skip other completions
7601	  ((save-excursion
7602	     ;; Check if the context is right for sysvar tag
7603	     (skip-chars-backward "a-zA-Z0-9_$.")
7604	     (and (equal (char-before) ?!)
7605		  (looking-at "\\([a-zA-Z][a-zA-Z0-9_$]*\\)\\.")
7606		  (<= (match-end 0) pos)))
7607	   ;; Complete a system variable tag
7608	   (let* ((var (idlwave-sintern-sysvar (match-string 1)))
7609		  (entry (assq var idlwave-system-variables-alist))
7610		  (tags (cdr (assq 'tags entry))))
7611	     (or entry (error "!%s is not a known system variable" var))
7612	     (or tags (error "System variable !%s is not a structure" var))
7613	     (setq idlwave-completion-help-info
7614		   (list 'idlwave-complete-sysvar-tag-help var))
7615	     (idlwave-complete-in-buffer 'sysvartag 'sysvartag
7616					 tags nil
7617					 "Select a system variable tag"
7618					 "system variable tag")
7619	     t)) ; return t to skip other completions
7620	  (t nil))))
7621
7622(defvar idlw-help-link) ;dynamic variables set by help callback
7623(defun idlwave-complete-sysvar-help (mode word)
7624  (let ((word (or (nth 1 idlwave-completion-help-info) word))
7625	(entry (assoc word idlwave-system-variables-alist)))
7626    (cond
7627     ((eq mode 'test)
7628      (and (stringp word) entry (nth 1 (assq 'link entry))))
7629     ((eq mode 'set)
7630      ;; Setting dynamic!!!
7631      (if entry (setq idlw-help-link (nth 1 (assq 'link entry)))))
7632     (t (error "This should not happen")))))
7633
7634(defun idlwave-complete-sysvar-tag-help (mode word)
7635  (let* ((var (nth 1 idlwave-completion-help-info))
7636	(entry (assoc var idlwave-system-variables-alist))
7637	(tags (cdr (assq 'tags entry)))
7638	(main (nth 1 (assq 'link entry)))
7639	target)
7640    (cond
7641     ((eq mode 'test) ; we can at least link the main
7642      (and (stringp word) entry main))
7643     ((eq mode 'set)
7644      (if entry
7645	  (setq idlw-help-link
7646		(if (setq target (cdr (assoc-string word tags t)))
7647		    (idlwave-substitute-link-target main target)
7648		  main)))) ;; setting dynamic!!!
7649     (t (error "This should not happen")))))
7650
7651(defun idlwave-split-link-target (link)
7652  "Split a given LINK into link file and anchor."
7653  (if (string-match idlwave-html-link-sep link)
7654      (cons (substring link 0 (match-beginning 0))
7655	    (string-to-number (substring link (match-end 0))))))
7656
7657(defun idlwave-substitute-link-target (link target)
7658  "Substitute the TARGET anchor for the given LINK."
7659  (let (main-base)
7660    (setq main-base (if (string-match "#" link)
7661			(substring link 0 (match-beginning 0))
7662		      link))
7663    (if target
7664	(concat main-base idlwave-html-link-sep (number-to-string target))
7665      link)))
7666
7667;; Fake help in the source buffer for class structure tags.
7668;; IDLW-HELP-LINK AND IDLW-HELP-NAME ARE GLOBAL-VARIABLES HERE.
7669;; (from idlwave-do-mouse-completion-help)
7670(defvar idlw-help-name)
7671(defvar idlw-help-link)
7672(defvar idlwave-help-do-class-struct-tag nil)
7673(defun idlwave-complete-class-structure-tag-help (mode word)
7674  (cond
7675   ((eq mode 'test) ; nothing gets fontified for class tags
7676    nil)
7677   ((eq mode 'set)
7678    (let (class-with found-in)
7679      (when (setq class-with
7680		(idlwave-class-or-superclass-with-tag
7681		 idlwave-current-tags-class
7682		 word))
7683	(if (assq (idlwave-sintern-class class-with)
7684		  idlwave-system-class-info)
7685	    (error "No help available for system class tags"))
7686	(if (setq found-in (idlwave-class-found-in class-with))
7687	    (setq idlw-help-name (cons (concat found-in "__define") class-with))
7688	  (setq idlw-help-name (concat class-with "__define")))))
7689    (setq idlw-help-link word
7690	  idlwave-help-do-class-struct-tag t))
7691   (t (error "This should not happen"))))
7692
7693(defun idlwave-class-or-superclass-with-tag (class tag)
7694  "Find and return the CLASS or one of its superclass with the
7695associated TAG, if any."
7696  (let ((sclasses (cons class (idlwave-all-class-inherits class)))
7697	cl)
7698   (catch 'exit
7699     (while sclasses
7700       (setq cl (pop sclasses))
7701       (let ((tags (idlwave-class-tags cl)))
7702	 (while tags
7703	   (if (eq t (compare-strings tag 0 nil (car tags) 0 nil t))
7704	     (throw 'exit cl))
7705	   (setq tags (cdr tags))))))))
7706
7707
7708(defun idlwave-sysvars-reset ()
7709  (if (and (fboundp 'idlwave-shell-is-running)
7710	   (idlwave-shell-is-running)
7711	   idlwave-idlwave_routine_info-compiled)
7712      (idlwave-shell-send-command "idlwave_get_sysvars"
7713				  'idlwave-process-sysvars 'hide)))
7714
7715(defun idlwave-process-sysvars ()
7716  (idlwave-shell-filter-sysvars)
7717  (setq idlwave-sint-sysvars nil
7718	idlwave-sint-sysvartags nil)
7719  (idlwave-sintern-sysvar-alist))
7720
7721(defun idlwave-sintern-sysvar-alist ()
7722  (let ((list idlwave-system-variables-alist) entry tags)
7723    (while (setq entry (pop list))
7724      (setcar entry (idlwave-sintern-sysvar (car entry) 'set))
7725      (setq tags (assq 'tags entry))
7726      (if tags
7727	  (setcdr tags
7728		  (mapcar (lambda (x)
7729			    (cons (idlwave-sintern-sysvartag (car x) 'set)
7730				  (cdr x)))
7731			  (cdr tags)))))))
7732
7733(defvar idlwave-shell-command-output)
7734(defun idlwave-shell-filter-sysvars ()
7735  "Get any new system variables and tags."
7736  (let ((text idlwave-shell-command-output)
7737	(start 0)
7738	(old idlwave-system-variables-alist)
7739	var tags type name class link old-entry)
7740    (setq idlwave-system-variables-alist nil)
7741    (while (string-match "^IDLWAVE-SYSVAR: !\\([a-zA-Z0-9_$]+\\)\\( \\(.*\\)\\)?"
7742			 text start)
7743      (setq start (match-end 0)
7744	    var (match-string 1 text)
7745	    tags (if (match-end 3)
7746		     (idlwave-split-string (match-string 3 text))))
7747      ;; Maintain old links, if present
7748      (setq old-entry (assq (idlwave-sintern-sysvar var) old))
7749      (setq link (assq 'link old-entry))
7750      (setq idlwave-system-variables-alist
7751	    (cons (list var
7752			(cons
7753			 'tags
7754			 (mapcar (lambda (x)
7755				   (cons x
7756					 (cdr (assq
7757					       (idlwave-sintern-sysvartag x)
7758					       (cdr (assq 'tags old-entry))))))
7759				 tags)) link)
7760		  idlwave-system-variables-alist)))
7761    ;; Keep the old value if query was not successful
7762    (setq idlwave-system-variables-alist
7763	  (or idlwave-system-variables-alist old))))
7764
7765(defun idlwave-completion-fontify-classes ()
7766  "Goto the *Completions* buffer and fontify the class info."
7767  (when (featurep 'font-lock)
7768    (with-current-buffer "*Completions*"
7769      (save-excursion
7770	(goto-char (point-min))
7771	(let ((buffer-read-only nil))
7772	  (while (re-search-forward "\\.*<[^>]+>" nil t)
7773	    (put-text-property (match-beginning 0) (match-end 0)
7774			       'face 'font-lock-string-face)))))))
7775
7776(defun idlwave-uniquify (list)
7777  (let ((ht (make-hash-table :size (length list) :test 'equal)))
7778    (delq nil
7779	  (mapcar (lambda (x)
7780		    (unless (gethash x ht)
7781		      (puthash x t ht)
7782		      x))
7783		  list))))
7784
7785(defun idlwave-after-successful-completion (type slash &optional verify)
7786  "Add `=' or `(' after successful completion of keyword and function.
7787Restore the pre-completion window configuration if possible."
7788  (cond
7789   ((eq type 'procedure)
7790    nil)
7791   ((eq type 'function)
7792    (cond
7793     ((equal idlwave-function-completion-adds-paren nil) nil)
7794     ((or (equal idlwave-function-completion-adds-paren t)
7795	  (equal idlwave-function-completion-adds-paren 1))
7796      (insert "("))
7797     ((equal idlwave-function-completion-adds-paren 2)
7798      (insert "()")
7799      (backward-char 1))
7800     (t nil)))
7801   ((eq type 'keyword)
7802    (if (and idlwave-keyword-completion-adds-equal
7803	     (not slash))
7804	(progn (insert "=") t)
7805      nil)))
7806
7807  ;; Restore the pre-completion window configuration if this is safe.
7808
7809  (if (or (eq verify 'force)                                    ; force
7810	  (and
7811	   (get-buffer-window "*Completions*")                  ; visible
7812	   (idlwave-local-value 'idlwave-completion-p
7813				"*Completions*")                ; cib-buffer
7814	   (eq (marker-buffer idlwave-completion-mark)
7815	       (current-buffer))                                ; buffer OK
7816	   (equal (marker-position idlwave-completion-mark)
7817		  verify)))                                     ; pos OK
7818      (idlwave-restore-wconf-after-completion))
7819  (move-marker idlwave-completion-mark nil)
7820  (setq idlwave-before-completion-wconf nil))
7821
7822(defun idlwave-mouse-context-help (ev &optional arg)
7823  "Call `idlwave-context-help' on the clicked location."
7824  (interactive "eP")
7825  (mouse-set-point ev)
7826  (idlwave-context-help arg))
7827
7828(defvar idlwave-last-context-help-pos nil)
7829(defun idlwave-context-help (&optional arg)
7830  "Display IDL Online Help on context.
7831If point is on a keyword, help for that keyword will be shown.  If
7832point is on a routine name or in the argument list of a routine, help
7833for that routine will be displayed.  Works for system routines and
7834keywords, it pulls up text help.  For other routines and keywords,
7835visits the source file, finding help in the header (if
7836`idlwave-help-source-try-header' is non-nil) or the routine definition
7837itself."
7838  (interactive "P")
7839  (idlwave-do-context-help arg))
7840
7841(defun idlwave-mouse-completion-help (ev)
7842  "Display online help about the completion at point."
7843  (interactive "eP")
7844  ;; Restore last-command for next command, to make
7845  ;; scrolling/canceling of completions work.
7846  (setq this-command last-command)
7847  (idlwave-do-mouse-completion-help ev))
7848
7849(defun idlwave-routine-info (&optional arg external)
7850  "Display a routines calling sequence and list of keywords.
7851When point is on the name a function or procedure, or in the argument
7852list of a function or procedure, this command displays a help buffer with
7853the information.  When called with prefix arg, enforce class query.
7854
7855When point is on an object operator `->', display the class stored in
7856this arrow, if any (see `idlwave-store-inquired-class').  With a prefix
7857arg, the class property is cleared out."
7858
7859  (interactive "P")
7860  (idlwave-routines)
7861  (if (string-match "->" (buffer-substring
7862			  (max (point-min) (1- (point)))
7863			  (min (+ 2 (point)) (point-max))))
7864      ;; Cursor is on an arrow
7865      (if (get-text-property (point) 'idlwave-class)
7866	  ;; arrow has class property
7867	  (if arg
7868	      ;; Remove property
7869	      (save-excursion
7870		(backward-char 1)
7871		(when (looking-at ".?\\(->\\)")
7872		  (remove-text-properties (match-beginning 1) (match-end 1)
7873					  '(idlwave-class nil face nil))
7874		  (message "Class property removed from arrow")))
7875	    ;; Echo class property
7876	    (message "Arrow has text property identifying object to be class %s"
7877		     (get-text-property (point) 'idlwave-class)))
7878	;; No property found
7879	(message "Arrow has no class text property"))
7880
7881    ;; Not on an arrow...
7882    (let* ((idlwave-query-class nil)
7883	   (idlwave-force-class-query (equal arg '(4)))
7884	   (module (idlwave-what-module)))
7885      (if (car module)
7886	  (apply 'idlwave-display-calling-sequence
7887		 (idlwave-fix-module-if-obj_new module))
7888	(error "Don't know which calling sequence to show")))))
7889
7890(defun idlwave-resolve (&optional arg)
7891  "Call RESOLVE_ROUTINE on the module name at point.
7892Like `idlwave-routine-info', this looks for a routine call at point.
7893After confirmation in the minibuffer, it will use the shell to issue
7894a RESOLVE call for this routine, to attempt to make it defined and its
7895routine info available for IDLWAVE.  If the routine is a method call,
7896both `class__method' and `class__define' will be tried.
7897With ARG, enforce query for the class of object methods."
7898  (interactive "P")
7899  (let* ((idlwave-query-class nil)
7900	 (idlwave-force-class-query (equal arg '(4)))
7901	 (module (idlwave-what-module))
7902	 (name (idlwave-make-full-name (nth 2 module) (car module)))
7903	 (type (if (eq (nth 1 module) 'pro) "pro" "function"))
7904	 (resolve (read-string "Resolve: " (format "%s %s" type name)))
7905	 (kwd "")
7906	 class)
7907    (if (string-match "\\(pro\\|function\\)[ \t]+\\(\\(.*\\)::\\)?\\(.*\\)"
7908		      resolve)
7909	(setq type (match-string 1 resolve)
7910	      class (if (match-beginning 2)
7911			(match-string 3 resolve)
7912		      nil)
7913	      name (match-string 4 resolve)))
7914    (if (string= (downcase type) "function")
7915	(setq kwd ",/is_function"))
7916
7917    (cond
7918     ((null class)
7919      (idlwave-shell-send-command
7920       (format "resolve_routine,'%s'%s" (downcase name) kwd)
7921       'idlwave-update-routine-info
7922       nil t))
7923     (t
7924      (idlwave-shell-send-command
7925       (format "resolve_routine,'%s__define'%s" (downcase class) kwd)
7926       (list 'idlwave-shell-send-command
7927	     (format "resolve_routine,'%s__%s'%s"
7928		     (downcase class) (downcase name) kwd)
7929	     '(idlwave-update-routine-info)
7930	     nil t))))))
7931
7932(defun idlwave-find-module-this-file ()
7933  (interactive)
7934  (idlwave-find-module '(4)))
7935
7936(defun idlwave-find-module (&optional arg)
7937  "Find the source code of an IDL module.
7938Works for modules for which IDLWAVE has routine info available.
7939The function offers as default the module name `idlwave-routine-info'
7940would use.  With ARG limit to this buffer.  With two prefix ARG's
7941force class query for object methods."
7942  (interactive "P")
7943  (let* ((idlwave-query-class nil)
7944	 (idlwave-force-class-query (equal arg '(16)))
7945	 (this-buffer (equal arg '(4)))
7946	 (module (idlwave-fix-module-if-obj_new (idlwave-what-module)))
7947	 (default (if module
7948		      (concat (idlwave-make-full-name
7949			       (nth 2 module) (car module))
7950			      (if (eq (nth 1 module) 'pro) "<p>" "<f>"))
7951		    "none"))
7952	 (list
7953	  (idlwave-uniquify
7954	   (delq nil
7955		 (mapcar (lambda (x)
7956			   (if (eq 'system (car-safe (nth 3 x)))
7957			       ;; Take out system routines with no source.
7958			       nil
7959			     (list
7960			      (concat (idlwave-make-full-name
7961				       (nth 2 x) (car x))
7962				      (if (eq (nth 1 x) 'pro) "<p>" "<f>")))))
7963			 (if this-buffer
7964			     (idlwave-save-buffer-update)
7965			   (idlwave-routines))))))
7966	 (name (idlwave-completing-read
7967		(if (or (not this-buffer)
7968			(assoc default list))
7969		    (format "Module (Default %s): " default)
7970		  (format "Module in this file: "))
7971		list))
7972	 type class)
7973    (if (string-match "\\`\\s-*\\'" name)
7974	;; Nothing, use the default.
7975	(setq name default))
7976    (if (string-match "<[fp]>" name)
7977	(setq type (substring name -2 -1)
7978	      name (substring name 0 -3)))
7979    (if (string-match "\\(.*\\)::\\(.*\\)" name)
7980	(setq class (match-string 1 name)
7981	      name (match-string 2 name)))
7982    (setq name (idlwave-sintern-routine-or-method name class)
7983	  class (idlwave-sintern-class class)
7984	  type (cond ((equal type "f") 'fun)
7985		     ((equal type "p") 'pro)
7986		     (t t)))
7987    (idlwave-do-find-module name type class nil this-buffer)))
7988
7989(defun idlwave-do-find-module (name type class
7990				    &optional force-source this-buffer)
7991  (let ((name1 (idlwave-make-full-name class name))
7992	source buf1 entry
7993	(buf (current-buffer))
7994	(pos (point))
7995	file name2)
7996    (setq entry (idlwave-best-rinfo-assq name type class (idlwave-routines)
7997					 'WITH-FILE)
7998	  source (or force-source (nth 3 entry))
7999	  name2 (if (nth 2 entry)
8000		    (idlwave-make-full-name (nth 2 entry) name)
8001		  name1))
8002    (if source
8003	(setq file (idlwave-routine-source-file source)))
8004    (unless file  ; Try to find it on the path.
8005      (setq file
8006	    (idlwave-expand-lib-file-name
8007	     (if class
8008		 (format "%s__define.pro" (downcase class))
8009	       (format "%s.pro" (downcase name))))))
8010    (cond
8011     ((or (null name) (equal name ""))
8012      (error "Abort"))
8013     ((eq (car source) 'system)
8014      (error "Source code for system routine %s is not available"
8015	     name2))
8016     ((or (not file) (not (file-regular-p file)))
8017      (error "Source code for routine %s is not available"
8018	     name2))
8019     (t
8020      (when (not this-buffer)
8021	(setq buf1
8022	      (idlwave-find-file-noselect file 'find))
8023	(pop-to-buffer buf1 t))
8024      (goto-char (point-max))
8025      (let ((case-fold-search t))
8026	(if (re-search-backward
8027	     (concat "^[ \t]*\\<"
8028		     (cond ((eq type 'fun) "function")
8029			   ((eq type 'pro) "pro")
8030			   (t "\\(pro\\|function\\)"))
8031		     "\\>[ \t]+"
8032		     (regexp-quote (downcase name2))
8033		     "[^a-zA-Z0-9_$]")
8034	     nil t)
8035	    (goto-char (match-beginning 0))
8036	  (pop-to-buffer buf)
8037	  (goto-char pos)
8038	  (error "Could not find routine %s" name2)))))))
8039
8040(defun idlwave-what-module ()
8041  "Return a default module for stuff near point.
8042Used by `idlwave-routine-info' and `idlwave-find-module'."
8043  (idlwave-routines)
8044  (if (let ((case-fold-search t))
8045	(save-excursion
8046	  (idlwave-beginning-of-statement)
8047	  (looking-at "[ \t]*\\(pro\\|function\\)[ \t]+\\(\\([a-zA-Z0-9_$]+\\)::\\)?\\([a-zA-Z0-9$_]+\\)\\([, \t\n]\\|$\\)")))
8048      ;; This is a function or procedure definition statement
8049      ;; We return the defined routine as module.
8050      (list
8051       (idlwave-sintern-routine-or-method (match-string-no-properties 4)
8052					  (match-string-no-properties 2))
8053       (if (equal (downcase (match-string 1)) "pro") 'pro 'fun)
8054       (idlwave-sintern-class (match-string 3)))
8055
8056    ;; Not a definition statement - analyze precise position.
8057    (let* ((where (idlwave-where))
8058	   (cw (nth 2 where))
8059	   (pro (car (nth 0 where)))
8060	   (func (car (nth 1 where)))
8061	   (this-word (idlwave-this-word "a-zA-Z0-9$_"))
8062	   (next-char (save-excursion (skip-chars-forward "a-zA-Z0-9$_")
8063				      (following-char)))
8064	   )
8065      (cond
8066       ((and (eq cw 'procedure)
8067	     (not (equal this-word "")))
8068	(setq this-word (idlwave-sintern-routine-or-method
8069			 this-word (nth 2 (nth 3 where))))
8070	(list this-word 'pro
8071	      (idlwave-determine-class
8072	       (cons this-word (cdr (nth 3 where)))
8073	       'pro)))
8074       ((and (eq cw 'function)
8075	     (not (equal this-word ""))
8076	     (or (eq next-char ?\()	; exclude arrays, vars.
8077		 (looking-at "[a-zA-Z0-9_]*[ \t]*(")))
8078	(setq this-word (idlwave-sintern-routine-or-method
8079			 this-word (nth 2 (nth 3 where))))
8080	(list this-word 'fun
8081	      (idlwave-determine-class
8082	       (cons this-word (cdr (nth 3 where)))
8083	       'fun)))
8084       ((and (memq cw '(function-keyword procedure-keyword))
8085	     (not (equal this-word ""))
8086	     (eq next-char ?\())	; A function!
8087	(setq this-word (idlwave-sintern-routine this-word))
8088	(list this-word 'fun nil))
8089       (func
8090	(list func 'fun (idlwave-determine-class (nth 1 where) 'fun)))
8091       (pro
8092	(list pro 'pro (idlwave-determine-class (nth 0 where) 'pro)))
8093       (t nil)))))
8094
8095(defun idlwave-what-module-find-class ()
8096  "Call `idlwave-what-module' and find the inherited class if necessary."
8097  (let* ((module (idlwave-what-module))
8098	 (class (nth 2 module)))
8099    (if (and (= (length module) 3)
8100	     (stringp class))
8101	(list (car module)
8102	      (nth 1 module)
8103	      (apply 'idlwave-find-inherited-class module))
8104      module)))
8105
8106(defun idlwave-find-inherited-class (name type class)
8107  "Find the class which defines TYPE NAME and is CLASS or inherited by CLASS."
8108  (let ((entry (idlwave-best-rinfo-assoc name type class (idlwave-routines))))
8109    (if entry
8110	(nth 2 entry)
8111      class)))
8112
8113(defun idlwave-fix-module-if-obj_new (module)
8114  "Check if MODULE points to obj_new.
8115If yes, and if the cursor is in the keyword region, change to the
8116appropriate Init method."
8117  (let* ((name (car module))
8118	 (pos (point))
8119	 (case-fold-search t)
8120	 string)
8121    (if (and (stringp name)
8122	     (equal (downcase name) "obj_new")
8123	     (save-excursion
8124	       (idlwave-beginning-of-statement)
8125	       (setq string (buffer-substring (point) pos))
8126	       (string-match "obj_new([^'\"]*['\"]\\([a-zA-Z0-9_]+\\)"
8127			     string)))
8128	(let ((name "Init")
8129	      (class (match-string 1 string)))
8130	  (setq module (list (idlwave-sintern-method "Init")
8131			     'fun
8132			     (idlwave-sintern-class class)))))
8133    module))
8134
8135(defun idlwave-fix-keywords (name type class keywords
8136				  &optional super-classes system)
8137  "Update a list of keywords.
8138Translate OBJ_NEW, adding all super-class keywords, or all keywords
8139from all classes if CLASS equals t.  If SYSTEM is non-nil, don't
8140demand _EXTRA in the keyword list."
8141  (let ((case-fold-search t))
8142
8143    ;; If this is the OBJ_NEW function, try to figure out the class and use
8144    ;; the keywords from the corresponding INIT method.
8145    (if (and (equal (upcase name) "OBJ_NEW")
8146	     (derived-mode-p 'idlwave-mode 'idlwave-shell-mode))
8147	(let* ((bos (save-excursion (idlwave-beginning-of-statement) (point)))
8148	       (string (buffer-substring bos (point)))
8149	       (case-fold-search t)
8150	       class)
8151	  (and (string-match "obj_new([^'\"]*['\"]\\([a-zA-Z0-9_]+\\)"
8152			     string)
8153	       (setq class (idlwave-sintern-class (match-string 1 string)))
8154	       (setq idlwave-current-obj_new-class class)
8155	       (setq keywords
8156		     (append keywords
8157			     (idlwave-entry-keywords
8158			      (idlwave-rinfo-assq
8159			       (idlwave-sintern-method "INIT")
8160			       'fun
8161			       class
8162			       (idlwave-routines)) 'do-link))))))
8163
8164    ;; If the class is t, combine all keywords of all methods NAME
8165    (when (eq class t)
8166      (mapc (lambda (entry)
8167	      (and
8168	       (nth 2 entry)             ; non-nil class
8169	       (eq (nth 1 entry) type)   ; correct type
8170	       (setq keywords
8171		     (append keywords
8172			     (idlwave-entry-keywords entry 'do-link)))))
8173	    (idlwave-all-assq name (idlwave-routines)))
8174      (setq keywords (idlwave-uniquify keywords)))
8175
8176    ;; If we have inheritance, add all keywords from superclasses, if
8177    ;; the user indicated that method in `idlwave-keyword-class-inheritance'
8178    (when (and
8179	   super-classes
8180	   idlwave-keyword-class-inheritance
8181	   (stringp class)
8182	   (or
8183	    system
8184	    (assq (idlwave-sintern-keyword "_extra") keywords)
8185	    (assq (idlwave-sintern-keyword "_ref_extra") keywords))
8186	   ;; Check if one of the keyword-class regexps matches the name
8187	   (let ((regexps idlwave-keyword-class-inheritance) re)
8188	     (catch 'exit
8189	       (while (setq re (pop regexps))
8190		 (if (string-match re name) (throw 'exit t))))))
8191
8192      (cl-loop for entry in (idlwave-routines) do
8193	    (and (nth 2 entry)                           ; non-nil class
8194		 (memq (nth 2 entry) super-classes)      ; an inherited class
8195		 (eq (nth 1 entry) type)                 ; correct type
8196		 (eq (car entry) name)                   ; correct name
8197		 (mapc (lambda (k) (add-to-list 'keywords k))
8198		       (idlwave-entry-keywords entry 'do-link))))
8199      (setq keywords (idlwave-uniquify keywords)))
8200
8201    ;; Return the final list
8202    keywords))
8203
8204(defun idlwave-expand-keyword (keyword module)
8205  "Expand KEYWORD to one of the valid keyword parameters of MODULE.
8206KEYWORD may be an exact match or an abbreviation of a keyword.
8207If the match is exact, KEYWORD itself is returned, even if there may be other
8208keywords of which KEYWORD is an abbreviation.  This is necessary because some
8209system routines have keywords which are prefixes of other keywords.
8210If KEYWORD is an abbreviation of several keywords, a list of all possible
8211completions is returned.
8212If the abbreviation was unique, the correct keyword is returned.
8213If it cannot be a keyword, the function return nil.
8214If we do not know about MODULE, just return KEYWORD literally."
8215  (let* ((name (car module))
8216	 (type (nth 1 module))
8217	 (class (nth 2 module))
8218	 (kwd (idlwave-sintern-keyword keyword))
8219	 (entry (idlwave-best-rinfo-assoc name type class (idlwave-routines)))
8220	 (kwd-alist (idlwave-entry-keywords entry))
8221	 (extra (or (assq (idlwave-sintern-keyword "_EXTRA") kwd-alist)
8222		    (assq (idlwave-sintern-keyword "_REF_EXTRA") kwd-alist)))
8223	 (completion-ignore-case t)
8224	 candidates)
8225    (cond ((assq kwd kwd-alist)
8226	   kwd)
8227	  ((setq candidates (all-completions kwd kwd-alist))
8228	   (if (= (length candidates) 1)
8229	       (car candidates)
8230	     candidates))
8231	  ((and entry extra)
8232	   ;; Inheritance may cause this keyword to be correct
8233	   keyword)
8234	  (entry
8235	   ;; We do know the function, which does not have the keyword.
8236	   nil)
8237	  (t
8238	   ;; We do not know the function, so this just might be a correct
8239	   ;; keyword - return it as it is.
8240	   keyword))))
8241
8242(defvar idlwave-rinfo-mouse-map
8243  (let ((map (make-sparse-keymap)))
8244    (define-key map
8245      (if (featurep 'xemacs) [button2] [mouse-2])
8246      'idlwave-mouse-active-rinfo)
8247    (define-key map
8248      (if (featurep 'xemacs) [(shift button2)] [(shift mouse-2)])
8249      'idlwave-mouse-active-rinfo-shift)
8250    (define-key map
8251      (if (featurep 'xemacs) [button3] [mouse-3])
8252      'idlwave-mouse-active-rinfo-right)
8253    (define-key map " " 'idlwave-active-rinfo-space)
8254    (define-key map "q" 'idlwave-quit-help)
8255    map))
8256
8257(defvar idlwave-rinfo-map
8258  (let ((map (make-sparse-keymap)))
8259    (define-key map "q" 'idlwave-quit-help)
8260    map))
8261
8262(defvar idlwave-popup-source nil)
8263(defvar idlwave-rinfo-marker (make-marker))
8264
8265(defun idlwave-quit-help ()
8266  (interactive)
8267  (let ((ri-window (get-buffer-window "*Help*"))
8268	(olh-window (get-buffer-window "*IDLWAVE Help*")))
8269    (when (and olh-window
8270	       (fboundp 'idlwave-help-quit))
8271      (select-window olh-window)
8272      (idlwave-help-quit))
8273    (when (window-live-p ri-window)
8274      (quit-window nil ri-window))))
8275
8276(defun idlwave-display-calling-sequence (name type class
8277					      &optional initial-class)
8278  ;; Display the calling sequence of module NAME, type TYPE in class CLASS.
8279  (let* ((initial-class (or initial-class class))
8280	 (entry (or (idlwave-best-rinfo-assq name type class
8281					     (idlwave-routines))
8282		    (idlwave-rinfo-assq name type class
8283					idlwave-unresolved-routines)))
8284	 (name (or (car entry) name))
8285	 (class (or (nth 2 entry) class))
8286	 (superclasses (idlwave-all-class-inherits initial-class))
8287	 (twins (idlwave-routine-twins entry))
8288	 (dtwins (idlwave-study-twins twins))
8289	 (all dtwins)
8290	 (system (eq (car (nth 3 entry)) 'system))
8291	 (calling-seq (nth 4 entry))
8292	 (keywords (idlwave-entry-keywords entry 'do-link))
8293	 (html-file (car (nth 5 entry)))
8294	 (help-echo-kwd
8295	  "Button2: Insert KEYWORD (SHIFT=`/KEYWORD') | Button3: Online Help ")
8296	 (help-echo-use
8297	  "Button2/3: Online Help")
8298	 (help-echo-src
8299	  "Button2: Jump to source and back | Button3: Source in Help window.")
8300	 (help-echo-class
8301	  "Button2: Display info about same method in superclass")
8302	 (col 0)
8303	 (data (list name type class (current-buffer) nil initial-class))
8304	 (km-prop (if (featurep 'xemacs) 'keymap 'local-map))
8305	 (face 'idlwave-help-link)
8306	 beg props win cnt total)
8307    ;; Fix keywords, but don't add chained super-classes, since these
8308    ;; are shown separately for that super-class
8309    (setq keywords (idlwave-fix-keywords name type class keywords))
8310    (cond
8311     ((null entry)
8312      (error "No %s %s known %s" type name
8313	     (if initial-class (concat "in class " initial-class) "")))
8314     ((or (null name) (equal name ""))
8315      (error "No function or procedure call at point"))
8316     ((null calling-seq)
8317      (error "Calling sequence of %s %s not available" type name))
8318     (t
8319      (move-marker idlwave-rinfo-marker (point))
8320      (with-current-buffer (get-buffer-create "*Help*")
8321	(use-local-map idlwave-rinfo-map)
8322	(setq buffer-read-only nil)
8323	(erase-buffer)
8324	(set (make-local-variable 'idlwave-popup-source) nil)
8325	(set (make-local-variable 'idlwave-current-obj_new-class)
8326				  idlwave-current-obj_new-class)
8327	(when superclasses
8328	  (setq props (list 'mouse-face 'highlight
8329			    km-prop idlwave-rinfo-mouse-map
8330			    'help-echo help-echo-class
8331			    'data (cons 'class data)))
8332	  (let ((classes (cons initial-class superclasses)) c)
8333	    (insert "Classes: ")
8334	    (while (setq c (pop classes))
8335	      (insert " ")
8336	      (setq beg (point))
8337	      (insert c)
8338	      (if (equal (downcase c) (downcase class))
8339		  (add-text-properties beg (point) (list 'face 'bold))
8340		;; If Method exists in a different class link it
8341		(if (idlwave-rinfo-assq name type c (idlwave-routines))
8342		    (add-text-properties beg (point) props))))
8343	    (insert "\n")))
8344	(setq props (list 'mouse-face 'highlight
8345			  km-prop idlwave-rinfo-mouse-map
8346			  'help-echo help-echo-use
8347			  'data (cons 'usage data)))
8348	(if html-file (setq props (append (list 'face face 'link html-file)
8349					  props)))
8350	(insert "Usage:    ")
8351	(setq beg (point))
8352	(insert (if class
8353		    (format calling-seq class name class name class name)
8354		  (format calling-seq name name name name))
8355		"\n")
8356	(add-text-properties beg (point) props)
8357
8358	(insert "Keywords:")
8359	(if (null keywords)
8360	    (insert " No keywords accepted.")
8361	  (setq col 9)
8362	  (mapc
8363	   (lambda (x)
8364	     (if (>= (+ col 1 (length (car x)))
8365		     (window-width))
8366		 (progn
8367		   (insert "\n         ")
8368		   (setq col 9)))
8369	     (insert " ")
8370	     (setq beg (point)
8371		   ;; Relevant keywords already have link property attached
8372		   props (list 'mouse-face 'highlight
8373			       km-prop idlwave-rinfo-mouse-map
8374			       'data (cons 'keyword data)
8375			       'help-echo help-echo-kwd
8376			       'keyword (car x)))
8377	     (if system (setq props (append (list 'face face) props)))
8378	     (insert (car x))
8379	     (add-text-properties beg (point) props)
8380	     (setq col (+ col 1 (length (car x)))))
8381	   keywords))
8382
8383	(setq cnt 1 total (length all))
8384	;; Here entry is (key file (list of type-conses))
8385	(while (setq entry (pop all))
8386	  (setq props (list 'mouse-face 'highlight
8387			    km-prop idlwave-rinfo-mouse-map
8388			    'help-echo help-echo-src
8389			    'source (list (car (car (nth 2 entry))) ;type
8390					  (nth 1 entry)
8391					  nil
8392					  (cdr (car (nth 2 entry))))
8393			    'data (cons 'source data)))
8394	  (idlwave-insert-source-location
8395	   (format "\n%-8s  %s"
8396		   (if (equal cnt 1)
8397		       (if (> total 1) "Sources:" "Source:")
8398		     "")
8399		   (if (> total 1) "- " ""))
8400	   entry props)
8401	  (cl-incf cnt)
8402	  (when (and all (> cnt idlwave-rinfo-max-source-lines))
8403	    ;; No more source lines, please
8404	    (insert (format
8405		     "\n          Source information truncated to %d entries."
8406		     idlwave-rinfo-max-source-lines))
8407	    (setq all nil)))
8408	(goto-char (point-min))
8409	(setq buffer-read-only t))
8410      (display-buffer "*Help*")
8411      (if (and (setq win (get-buffer-window "*Help*"))
8412	       idlwave-resize-routine-help-window)
8413	  (progn
8414	    (let ((ww (selected-window)))
8415	      (unwind-protect
8416		  (progn
8417		    (select-window win)
8418		    (enlarge-window (- (/ (frame-height) 2)
8419				       (window-height)))
8420		    (shrink-window-if-larger-than-buffer))
8421		(select-window ww)))))))))
8422
8423(defun idlwave-insert-source-location (prefix entry &optional file-props)
8424  "Insert a source location into the routine info buffer.
8425Start line with PREFIX.  If a file name is inserted, add FILE-PROPS
8426to it."
8427  (let* ((key (car entry))
8428	 (file (nth 1 entry))
8429	 (types (nth 2 entry))
8430	 (shell-flag (assq 'compiled types))
8431	 (buffer-flag (assq 'buffer types))
8432	 (user-flag (assq 'user types))
8433	 (lib-flag (assq 'lib types))
8434	 (ndupl (or (and buffer-flag (idlwave-count-memq 'buffer types))
8435		    (and user-flag (idlwave-count-memq 'user types))
8436		    (and lib-flag (idlwave-count-memq 'lib types))
8437		    1))
8438	 (doflags t)
8439	 beg special)
8440
8441    (insert prefix)
8442
8443    (cond
8444     ((eq key 'system)
8445      (setq doflags nil)
8446      (insert "System    "))
8447
8448     ((eq key 'builtin)
8449      (setq doflags nil)
8450      (insert "Builtin   "))
8451
8452     ((and (not file) shell-flag)
8453      (insert "Unresolved"))
8454
8455     ((null file)
8456      (insert "ERROR"))
8457
8458     ((idlwave-syslib-p file)
8459      (if (string-match "obsolete" (file-name-directory file))
8460	  (insert "Obsolete  ")
8461	(insert "SystemLib ")))
8462
8463     ;; New special syntax: taken directly from routine-info for
8464     ;; library catalog routines
8465     ((setq special (or (cdr lib-flag) (cdr user-flag)))
8466      (insert (format "%-10s" special)))
8467
8468     ;; Old special syntax: a matching regexp
8469     ((setq special (idlwave-special-lib-test file))
8470      (insert (format "%-10s" special)))
8471
8472     ;; Catch-all with file
8473     ((idlwave-lib-p file)      (insert "Library   "))
8474
8475     ;; Sanity catch all
8476     (t                         (insert "Other     ")))
8477
8478    (when doflags
8479      (insert (concat
8480	       "  ["
8481	       (if lib-flag "L" "-")
8482	       (if user-flag "C" "-")
8483	       (if shell-flag "S" "-")
8484	       (if buffer-flag "B" "-")
8485	       "] ")))
8486    (when (> ndupl 1)
8487      (setq beg (point))
8488      (insert (format "(%dx) " ndupl))
8489      (add-text-properties beg (point) (list 'face 'bold)))
8490    (when (and file (not (equal file "")))
8491      (setq beg (point))
8492      (insert (apply 'abbreviate-file-name
8493		     (if (featurep 'xemacs) (list file t) (list file))))
8494      (if file-props
8495	  (add-text-properties beg (point) file-props)))))
8496
8497(defun idlwave-special-lib-test (file)
8498  "Check the path of FILE against the regexps which define special libs.
8499Return the name of the special lib if there is a match."
8500  (let ((alist idlwave-special-lib-alist)
8501	entry rtn)
8502    (cond
8503     ((stringp file)
8504      (while (setq entry (pop alist))
8505	(if (string-match (car entry) file)
8506	    (setq rtn (cdr entry)
8507		  alist nil)))
8508      rtn)
8509     (t nil))))
8510
8511(defun idlwave-mouse-active-rinfo-right (ev)
8512  (interactive "e")
8513  (idlwave-mouse-active-rinfo ev 'right))
8514
8515(defun idlwave-mouse-active-rinfo-shift (ev)
8516  (interactive "e")
8517  (idlwave-mouse-active-rinfo ev nil 'shift))
8518
8519(defun idlwave-active-rinfo-space ()
8520  (interactive)
8521  (idlwave-mouse-active-rinfo nil 'right))
8522
8523(defun idlwave-mouse-active-rinfo (ev &optional right shift)
8524  "Do the mouse actions in the routine info buffer.
8525Optional args RIGHT and SHIFT indicate, if mouse-3 was used, and if SHIFT
8526was pressed."
8527  (interactive "e")
8528  (if ev (mouse-set-point ev))
8529  (let (data id name type class buf bufwin source link keyword
8530	     word initial-class)
8531    (setq data (get-text-property (point) 'data)
8532	  source (get-text-property (point) 'source)
8533	  keyword (get-text-property (point) 'keyword)
8534	  link (get-text-property (point) 'link)
8535	  id (car data)
8536	  name (nth 1 data) type (nth 2 data) class (nth 3 data)
8537	  buf (nth 4 data)
8538	  initial-class (nth 6 data)
8539	  word (idlwave-this-word)
8540	  bufwin (get-buffer-window buf t))
8541
8542    (cond ((eq id 'class) ; Switch class being displayed
8543	   (if (window-live-p bufwin) (select-window bufwin))
8544	   (idlwave-display-calling-sequence
8545	    (idlwave-sintern-method name)
8546	    type (idlwave-sintern-class word)
8547	    initial-class))
8548	  ((eq id 'usage) ; Online help on this routine
8549	   (idlwave-online-help link name type class))
8550	  ((eq id 'source) ; Source in help or buffer
8551	   (if right ; In help
8552	       (let ((idlwave-extra-help-function 'idlwave-help-with-source)
8553		     (idlwave-help-source-try-header nil)
8554		     ;; Fake idlwave-routines so help will find the right entry
8555		     (idlwave-routines
8556		      (list (list name type class source ""))))
8557		 (idlwave-help-get-special-help name type class nil))
8558	     ;; Otherwise just pop to the source
8559	     (setq idlwave-popup-source (not idlwave-popup-source))
8560	     (if idlwave-popup-source
8561		 (condition-case err
8562		     (idlwave-do-find-module name type class source)
8563		   (error
8564		    (setq idlwave-popup-source nil)
8565		    (if (window-live-p bufwin) (select-window bufwin))
8566		    (error (nth 1 err))))
8567	       (if bufwin
8568		   (select-window bufwin)
8569		 (pop-to-buffer buf))
8570	       (goto-char (marker-position idlwave-rinfo-marker)))))
8571	  ((eq id 'keyword)
8572	   (if right
8573	       (idlwave-online-help link name type class keyword)
8574	     (idlwave-rinfo-insert-keyword keyword buf shift))))))
8575
8576(defun idlwave-rinfo-insert-keyword (keyword buffer &optional shift)
8577  "Insert KEYWORD in BUFFER.  Make sure buffer is displayed in a window."
8578  (let ((bwin (get-buffer-window buffer)))
8579    (if idlwave-complete-empty-string-as-lower-case
8580	(setq keyword (downcase keyword)))
8581    (if bwin
8582	(select-window bwin)
8583      (pop-to-buffer buffer)
8584      (setq bwin (get-buffer-window buffer)))
8585    (if (eq (preceding-char) ?/)
8586	(insert keyword)
8587      (unless (save-excursion
8588		(re-search-backward
8589		 "[(,][ \t]*\\(\\$[ \t]*\\(;.*\\)?\n\\)?[ \t]*\\="
8590		 (min (- (point) 100) (point-min)) t))
8591	(insert ", "))
8592      (if shift (insert "/"))
8593      (insert keyword)
8594      (if (and (not shift)
8595	       idlwave-keyword-completion-adds-equal)
8596	  (insert "=")))))
8597
8598(defun idlwave-list-buffer-load-path-shadows (&optional arg)
8599  "List the load path shadows of all routines defined in current buffer."
8600  (interactive "P")
8601  (idlwave-routines)
8602  (if (derived-mode-p 'idlwave-mode)
8603      (idlwave-list-load-path-shadows
8604       nil (idlwave-update-current-buffer-info 'save-buffer)
8605       "in current buffer")
8606    (error "Current buffer is not in idlwave-mode")))
8607
8608(defun idlwave-list-shell-load-path-shadows (&optional arg)
8609  "List the load path shadows of all routines compiled under the shell.
8610This is very useful for checking an IDL application.  Just compile the
8611application, do RESOLVE_ALL, and `C-c C-i' to compile all referenced
8612routines and update IDLWAVE internal info.  Then check for shadowing
8613with this command."
8614  (interactive "P")
8615  (cond
8616   ((or (not (fboundp 'idlwave-shell-is-running))
8617	(not (idlwave-shell-is-running)))
8618    (error "Shell is not running"))
8619   ((null idlwave-compiled-routines)
8620    (error "No compiled routines.  Maybe you need to update with `C-c C-i'"))
8621   (t
8622    (idlwave-list-load-path-shadows nil idlwave-compiled-routines
8623				    "in the shell"))))
8624
8625(defun idlwave-list-all-load-path-shadows (&optional arg)
8626  "List the load path shadows of all routines known to IDLWAVE."
8627  (interactive "P")
8628  (idlwave-list-load-path-shadows nil nil "globally"))
8629
8630(defvar idlwave-sort-prefer-buffer-info t
8631  "Internal variable used to influence `idlwave-routine-twin-compare'.")
8632
8633(defun idlwave-list-load-path-shadows (arg &optional special-routines loc)
8634  "List the routines which are defined multiple times.
8635Search the information IDLWAVE has about IDL routines for multiple
8636definitions.
8637When SPECIAL-ROUTINES in non-nil, only look for shadows of these routines.
8638
8639When IDL hits a routine call which is not defined, it will search on
8640the load path in order to find a definition.  The output of this command
8641can be used to detect possible name clashes during this process."
8642  (idlwave-routines)  ; Make sure everything is loaded.
8643  (unless (or idlwave-user-catalog-routines idlwave-library-catalog-routines)
8644    (or (y-or-n-p
8645	 "You don't have any user or library catalogs.  Continue anyway? ")
8646	(error "Abort")))
8647  (let* ((routines (append idlwave-system-routines
8648			   idlwave-compiled-routines
8649			   idlwave-library-catalog-routines
8650			   idlwave-user-catalog-routines
8651			   idlwave-buffer-routines
8652			   nil))
8653	 (km-prop (if (featurep 'xemacs) 'keymap 'local-map))
8654	 (keymap (make-sparse-keymap))
8655	 (props (list 'mouse-face 'highlight
8656		      km-prop keymap
8657		      'help-echo "Mouse2: Find source"))
8658	 (nroutines (length (or special-routines routines)))
8659	 (step (/ nroutines 100))
8660	 (n 0)
8661	 (cnt 0)
8662	 (idlwave-sort-prefer-buffer-info nil)
8663	 routine twins dtwins twin done props1 lroutines)
8664
8665    (if special-routines
8666	;; Just looking for shadows of a few special routines
8667	(setq lroutines routines
8668	      routines special-routines))
8669
8670    (message "Sorting routines...")
8671    (setq routines (sort routines
8672			 (lambda (a b)
8673			   (string< (downcase (idlwave-make-full-name
8674					       (nth 2 a) (car a)))
8675				    (downcase (idlwave-make-full-name
8676					       (nth 2 b) (car b)))))))
8677    (message "Sorting routines...done")
8678
8679    (define-key keymap (if (featurep 'xemacs) [(button2)] [(mouse-2)])
8680      (lambda (ev)
8681	(interactive "e")
8682	(mouse-set-point ev)
8683	(apply 'idlwave-do-find-module
8684	       (get-text-property (point) 'find-args))))
8685    (define-key keymap [(return)]
8686      (lambda ()
8687	(interactive)
8688	(apply 'idlwave-do-find-module
8689	       (get-text-property (point) 'find-args))))
8690    (message "Compiling list...( 0%%)")
8691    (with-current-buffer (get-buffer-create "*Shadows*")
8692      (setq buffer-read-only nil)
8693      (erase-buffer)
8694      (while (setq routine (pop routines))
8695	(if (= (mod (setq n (1+ n)) step) 0)
8696	    (message "Compiling list...(%2d%%)" (floor (* n 100.0) nroutines)))
8697
8698	;; Get a list of all twins
8699	(setq twins (idlwave-routine-twins routine (or lroutines routines)))
8700	(if (memq routine done)
8701	    (setq dtwins nil)
8702	  (setq dtwins (idlwave-study-twins twins)))
8703	;; Mark all twins as dealt with
8704	(setq done (append twins done))
8705	(when (or (> (length dtwins) 1)
8706		  (> (idlwave-count-memq 'lib (nth 2 (car dtwins))) 1)
8707		  (> (idlwave-count-memq 'user (nth 2 (car dtwins))) 1)
8708		  (> (idlwave-count-memq 'buffer (nth 2 (car dtwins))) 1))
8709	  (cl-incf cnt)
8710	  (insert (format "\n%s%s"
8711			  (idlwave-make-full-name (nth 2 routine)
8712						  (car routine))
8713			  (if (eq (nth 1 routine) 'fun) "()" "")))
8714	  (while (setq twin (pop dtwins))
8715	    (setq props1 (append (list 'find-args
8716				       (list (nth 0 routine)
8717					     (nth 1 routine)
8718					     (nth 2 routine)))
8719				 props))
8720	    (idlwave-insert-source-location "\n   - " twin props1))))
8721      (goto-char (point-min))
8722      (setq buffer-read-only t))
8723    (setq loc (or loc ""))
8724    (if (> cnt 0)
8725	(progn
8726	  (display-buffer (get-buffer "*Shadows*"))
8727	  (message "%d case%s of shadowing found %s"
8728		   cnt (if (= cnt 1) "" "s") loc))
8729      (message "No shadowing conflicts found %s" loc))))
8730
8731(defun idlwave-print-source (routine)
8732  (let* ((source (nth 3 routine))
8733	 (stype (car source))
8734	 (sfile (idlwave-routine-source-file source)))
8735    (if (idlwave-syslib-p sfile) (setq stype 'syslib))
8736    (if (and (eq stype 'compiled)
8737	     (or (not (stringp sfile))
8738		 (not (string-match "\\S-" sfile))))
8739	(setq stype 'unresolved))
8740    (princ (format "      %-10s %s\n"
8741		   stype
8742		   (if sfile sfile "No source code available")))))
8743
8744(defun idlwave-routine-twins (entry &optional list)
8745  "Return all twin entries of ENTRY in LIST.
8746LIST defaults to `idlwave-routines'.
8747Twin entries are those which have the same name, type, and class.
8748ENTRY will also be returned, as the first item of this list."
8749  (let* ((name (car entry))
8750	 (type (nth 1 entry))
8751	 (class (nth 2 entry))
8752	 (candidates (idlwave-all-assq name (or list (idlwave-routines))))
8753	 twins candidate)
8754    (while (setq candidate (pop candidates))
8755      (if (and (not (eq candidate entry))
8756	       (eq type (nth 1 candidate))
8757	       (eq class (nth 2 candidate)))
8758	  (push candidate twins)))
8759    (if (setq candidate (idlwave-rinfo-assq name type class
8760					    idlwave-unresolved-routines))
8761	(push candidate twins))
8762    (cons entry (nreverse twins))))
8763
8764(defun idlwave-study-twins (entries)
8765  "Return dangerous twins of first entry in ENTRIES.
8766Dangerous twins are routines with same name, but in different files on
8767the load path.  If a file is in the system library and has an entry in
8768the `idlwave-system-routines' list, we omit the latter as
8769non-dangerous because many IDL routines are implemented as library
8770routines, and may have been scanned."
8771  (let* ((entry (car entries))
8772	 (idlwave-twin-name (car entry))      ;
8773	 (type (nth 1 entry))    ; Must be bound for
8774	 (idlwave-twin-class (nth 2 entry)) ;  idlwave-routine-twin-compare
8775	 (cnt 0)
8776	 source type type-cons file alist syslibp key)
8777    (while (setq entry (pop entries))
8778      (cl-incf cnt)
8779      (setq source (nth 3 entry)
8780	    type (car source)
8781	    type-cons (cons type (nth 3 source))
8782	    file (idlwave-routine-source-file source))
8783
8784      ;; Make KEY to index entry properly
8785      (setq key (cond ((eq type 'system) type)
8786		      (file (file-truename file))
8787		      (t 'unresolved)))
8788
8789      ;; Check for an entry in the system library
8790      (if (and file
8791	       (not syslibp)
8792	       (idlwave-syslib-p file))
8793	  (setq syslibp t))
8794
8795      ;; If there's more than one matching entry for the same file, just
8796      ;; append the type-cons to the type list.
8797      (if (setq entry (assoc key alist))
8798	  (push type-cons (nth 2 entry))
8799	(push (list key file (list type-cons)) alist)))
8800
8801    (setq alist (nreverse alist))
8802
8803    (when syslibp
8804      ;; File is in system *library* - remove any 'system entry
8805      (setq alist (delq (assq 'system alist) alist)))
8806
8807    ;; If 'system remains and we've scanned the syslib, it's a builtin
8808    ;; (rather than a !DIR/lib/.pro file bundled as source).
8809    (when (and (idlwave-syslib-scanned-p)
8810	       (setq entry (assoc 'system alist)))
8811      (setcar entry 'builtin))
8812    (sort alist 'idlwave-routine-twin-compare)))
8813
8814;; FIXME: Dynamically scoped vars need to use the `idlwave-' prefix.
8815;; (defvar type)
8816
8817(define-obsolete-function-alias 'idlwave-xor 'xor "27.1")
8818
8819(defun idlwave-routine-entry-compare (a b)
8820  "Compare two routine info entries for sorting.
8821This is the general case.  It first compares class, names, and type.
8822If it turns out that A and B are twins (same name, class, and type),
8823calls another routine which compares twins on the basis of their file
8824names and path locations."
8825  (let ((name (car a)) (type (nth 1 a)) (class (nth 2 a)))
8826    (cond
8827     ((not (equal (idlwave-downcase-safe class)
8828		  (idlwave-downcase-safe (nth 2 b))))
8829      ;; Class decides
8830      (cond ((null (nth 2 b)) nil)
8831	    ((null class) t)
8832	    (t (string< (downcase class) (downcase (nth 2 b))))))
8833     ((not (equal (downcase name) (downcase (car b))))
8834      ;; Name decides
8835      (string< (downcase name) (downcase (car b))))
8836     ((not (eq type (nth 1 b)))
8837      ;; Type decides
8838      (< (if (eq type 'fun) 1 0) (if (eq (nth 1 b) 'fun) 1 0)))
8839     (t
8840      ;; A and B are twins - so the decision is more complicated.
8841      ;; Call twin-compare with the proper arguments.
8842      (idlwave-routine-entry-compare-twins a b)))))
8843
8844(defun idlwave-routine-entry-compare-twins (a b)
8845  "Compare two routine entries, under the assumption that they are twins.
8846This basically calls `idlwave-routine-twin-compare' with the correct args."
8847  (let* ((idlwave-twin-name (car a))
8848	 (type (nth 1 a))
8849	 (idlwave-twin-class (nth 2 a)) ; used in idlwave-routine-twin-compare
8850	 (asrc (nth 3 a))
8851	 (atype (car asrc))
8852	 (bsrc (nth 3 b))
8853	 (btype (car bsrc))
8854	 (afile (idlwave-routine-source-file asrc))
8855	 (bfile (idlwave-routine-source-file bsrc)))
8856    (idlwave-routine-twin-compare
8857     (if (stringp afile)
8858	 (list (file-truename afile) afile (list atype))
8859       (list atype afile (list atype)))
8860     (if (stringp bfile)
8861	 (list (file-truename bfile) bfile (list btype))
8862       (list btype bfile (list btype))))))
8863
8864;; Bound in idlwave-study-twins,idlwave-routine-entry-compare-twins.
8865(defvar idlwave-twin-class)
8866(defvar idlwave-twin-name)
8867
8868(defun idlwave-routine-twin-compare (a b)
8869  "Compare two routine twin entries for sorting.
8870In here, A and B are not normal routine info entries, but special
8871lists (KEY FILENAME (TYPES...)).
8872This expects NAME TYPE IDLWAVE-TWIN-CLASS to be bound to the right values."
8873  (let* (;; Dis-assemble entries
8874	 (akey (car a))	     (bkey (car b))
8875	 (afile (nth 1 a))   (bfile (nth 1 b))
8876	 (atypes (nth 2 a))  (btypes (nth 2 b))
8877	 ;; System routines?
8878	 (asysp (memq akey '(builtin system)))
8879	 (bsysp (memq bkey '(builtin system)))
8880	 ;; Compiled routines?
8881	 (acompp (memq 'compiled atypes))
8882	 (bcompp (memq 'compiled btypes))
8883	 ;; Unresolved?
8884	 (aunresp (or (eq akey 'unresolved)
8885		      (and acompp (not afile))))
8886	 (bunresp (or (eq bkey 'unresolved)
8887		      (and bcompp (not bfile))))
8888	 ;; Buffer info available?
8889	 (abufp (memq 'buffer atypes))
8890	 (bbufp (memq 'buffer btypes))
8891	 ;; On search path?
8892	 (tpath-alist (idlwave-true-path-alist))
8893	 (apathp (and (stringp akey)
8894		      (assoc (file-name-directory akey) tpath-alist)))
8895	 (bpathp (and (stringp bkey)
8896		      (assoc (file-name-directory bkey) tpath-alist)))
8897	 ;; How early on search path?  High number means early since we
8898	 ;; measure the tail of the path list
8899	 (anpath (length (memq apathp tpath-alist)))
8900	 (bnpath (length (memq bpathp tpath-alist)))
8901	 ;; Look at file names
8902	 (aname (if (stringp afile) (downcase (file-name-nondirectory afile)) ""))
8903	 (bname (if (stringp bfile) (downcase (file-name-nondirectory bfile)) ""))
8904	 (fname-re (if idlwave-twin-class
8905		       (format "\\`%s__\\(%s\\|define\\)\\.pro\\'"
8906			       (regexp-quote (downcase idlwave-twin-class))
8907			       (regexp-quote (downcase idlwave-twin-name)))
8908		     (format "\\`%s\\.pro" (regexp-quote (downcase idlwave-twin-name)))))
8909	 ;; Is file name derived from the routine name?
8910	 ;; Method file or class definition file?
8911	 (anamep (string-match fname-re aname))
8912	 (adefp (and idlwave-twin-class anamep
8913		     (string= "define" (match-string 1 aname))))
8914	 (bnamep (string-match fname-re bname))
8915	 (bdefp (and idlwave-twin-class bnamep
8916		     (string= "define" (match-string 1 bname)))))
8917
8918    ;; Now: follow JD's ideas about sorting.  Looks really simple now,
8919    ;; doesn't it?  The difficult stuff is hidden above...
8920    (cond
8921     ((xor asysp   bsysp)     asysp)        ; System entries first
8922     ((xor aunresp bunresp)   bunresp)      ; Unresolved last
8923     ((and idlwave-sort-prefer-buffer-info
8924           (xor abufp bbufp)) abufp)        ; Buffers before non-buffers
8925     ((xor acompp bcompp)     acompp)       ; Compiled entries
8926     ((xor apathp bpathp)     apathp)       ; Library before non-library
8927     ((xor anamep bnamep)     anamep)       ; Correct file names first
8928     ((and idlwave-twin-class anamep bnamep ; both file names match ->
8929           (xor adefp bdefp)) bdefp)        ; __define after __method
8930     ((> anpath bnpath)       t)            ; Who is first on path?
8931     (t                       nil))))       ; Default
8932
8933(defun idlwave-routine-source-file (source)
8934  (if (nth 2 source)
8935      (expand-file-name (nth 1 source) (nth 2 source))
8936    (nth 1 source)))
8937
8938(defun idlwave-downcase-safe (string)
8939  "Downcase if string, else return unchanged."
8940  (if (stringp string)
8941      (downcase string)
8942    string))
8943
8944(defun idlwave-count-eq (elt list)
8945  "How often is ELT in LIST?"
8946  (length (delq nil (mapcar (lambda (x) (eq x elt)) list))))
8947
8948(defun idlwave-count-memq (elt alist)
8949  "How often is ELT a key in ALIST?"
8950  (length (delq nil (mapcar (lambda (x) (eq (car x) elt)) alist))))
8951
8952(defun idlwave-syslib-p (file)
8953  "Non-nil if FILE is in the system library."
8954  (let* ((true-syslib (file-name-as-directory
8955		       (file-truename
8956			(expand-file-name "lib" (idlwave-sys-dir)))))
8957	 (true-file (file-truename file)))
8958    (string-match (concat "^" (regexp-quote true-syslib)) true-file)))
8959
8960(defun idlwave-lib-p (file)
8961  "Non-nil if FILE is in the library."
8962  (let ((true-dir (file-name-directory (file-truename file))))
8963    (assoc true-dir (idlwave-true-path-alist))))
8964
8965(defun idlwave-path-alist-add-flag (list-entry flag)
8966  "Add a flag to the path list entry, if not set."
8967  (let ((flags (cdr list-entry)))
8968    (add-to-list 'flags flag)
8969    (setcdr list-entry flags)))
8970
8971(defun idlwave-path-alist-remove-flag (list-entry flag)
8972  "Remove a flag to the path list entry, if set."
8973  (let ((flags (delq flag (cdr list-entry))))
8974    (setcdr list-entry flags)))
8975
8976(defun idlwave-true-path-alist ()
8977  "Return `idlwave-path-alist' alist with true-names.
8978Info is cached, but relies on the functions setting `idlwave-path-alist'
8979to reset the variable `idlwave-true-path-alist' to nil."
8980  (or idlwave-true-path-alist
8981      (setq idlwave-true-path-alist
8982	    (mapcar (lambda(x) (cons
8983				(file-name-as-directory
8984				 (file-truename
8985				  (directory-file-name
8986				   (car x))))
8987				(cdr x)))
8988		    idlwave-path-alist))))
8989
8990(defun idlwave-syslib-scanned-p ()
8991  "Non-nil if the system lib file !DIR/lib has been scanned."
8992  (let* ((true-syslib (file-name-as-directory
8993		       (file-truename
8994			(expand-file-name "lib" (idlwave-sys-dir))))))
8995    (cdr (assoc true-syslib (idlwave-true-path-alist)))))
8996
8997;; ----------------------------------------------------------------------------
8998;;
8999;; Online Help display
9000
9001
9002;; ----------------------------------------------------------------------------
9003;;
9004;; Additions for use with imenu.el and func-menu.el
9005;; (pop-up a list of IDL units in the current file).
9006;;
9007
9008(defun idlwave-prev-index-position ()
9009  "Search for the previous procedure or function.
9010Return nil if not found.  For use with imenu.el."
9011  (save-match-data
9012    (cond
9013     ((idlwave-find-key "\\<\\(pro\\|function\\)\\>" -1 'nomark))
9014     ;;   ((idlwave-find-key idlwave-begin-unit-reg 1 'nomark)
9015     (t nil))))
9016
9017(defun idlwave-unit-name ()
9018  "Return the unit name.
9019Assumes that point is at the beginning of the unit as found by
9020`idlwave-prev-index-position'."
9021  (forward-sexp 2)
9022  (forward-sexp -1)
9023  (let ((begin (point)))
9024    (re-search-forward
9025     "[a-zA-Z_][a-zA-Z0-9$_]+\\(::[a-zA-Z_][a-zA-Z0-9$_]+\\)?")
9026    (if (fboundp 'buffer-substring-no-properties)
9027        (buffer-substring-no-properties begin (point))
9028      (buffer-substring begin (point)))))
9029
9030(defalias 'idlwave-function-menu
9031  (condition-case nil
9032      (progn
9033	(require 'func-menu)
9034	'function-menu)
9035    (error (condition-case nil
9036	       (progn
9037		 (require 'imenu)
9038		 'imenu)
9039	     (error nil)))))
9040
9041;; Here we hack func-menu.el in order to support this new mode.
9042;; The latest versions of func-menu.el already have this stuff in, so
9043;; we hack only if it is not already there.
9044(when (featurep 'xemacs)
9045  (eval-after-load "func-menu"
9046    '(progn
9047       (or (assq 'idlwave-mode fume-function-name-regexp-alist)
9048	   (not (boundp 'fume-function-name-regexp-idl))      ; avoid problems
9049	   (setq fume-function-name-regexp-alist
9050		 (cons '(idlwave-mode . fume-function-name-regexp-idl)
9051		       fume-function-name-regexp-alist)))
9052       (or (assq 'idlwave-mode fume-find-function-name-method-alist)
9053	   (not (fboundp 'fume-find-next-idl-function-name))  ; avoid problems
9054	   (setq fume-find-function-name-method-alist
9055		 (cons '(idlwave-mode . fume-find-next-idl-function-name)
9056		       fume-find-function-name-method-alist))))))
9057
9058(defun idlwave-edit-in-idlde ()
9059  "Edit the current file in IDL Development environment."
9060  (interactive)
9061  (start-process "idldeclient" nil
9062		 idlwave-shell-explicit-file-name "-c" "-e"
9063                 (buffer-file-name)))
9064
9065(defvar idlwave-help-use-assistant)
9066(defun idlwave-launch-idlhelp ()
9067  "Start the IDLhelp application."
9068  (interactive)
9069  (if idlwave-help-use-assistant
9070      (idlwave-help-assistant-raise)
9071    (start-process "idlhelp" nil idlwave-help-application)))
9072
9073;; Menus - using easymenu.el
9074(defvar idlwave-mode-menu-def
9075  '("IDLWAVE"
9076    ["PRO/FUNC menu" idlwave-function-menu t]
9077    ("Motion"
9078     ["Subprogram Start" idlwave-beginning-of-subprogram t]
9079     ["Subprogram End" idlwave-end-of-subprogram t]
9080     ["Block Start" idlwave-beginning-of-block t]
9081     ["Block End" idlwave-end-of-block t]
9082     ["Up Block" idlwave-backward-up-block t]
9083     ["Down Block" idlwave-down-block t]
9084     ["Skip Block Backward" idlwave-backward-block t]
9085     ["Skip Block Forward" idlwave-forward-block t])
9086    ("Mark"
9087     ["Subprogram" idlwave-mark-subprogram t]
9088     ["Block" idlwave-mark-block t]
9089     ["Header" idlwave-mark-doclib t])
9090    ("Format"
9091     ["Indent Entire Statement" idlwave-indent-statement
9092      :active t :keys "C-u \\[indent-for-tab-command]" ]
9093     ["Indent Subprogram" idlwave-indent-subprogram t]
9094     ["(Un)Comment Region" idlwave-toggle-comment-region t]
9095     ["Continue/Split line" idlwave-split-line t]
9096     "--"
9097     ["Toggle Auto Fill" idlwave-auto-fill-mode :style toggle
9098      :selected (symbol-value idlwave-fill-function)])
9099    ("Templates"
9100     ["Procedure" idlwave-procedure t]
9101     ["Function" idlwave-function t]
9102     ["Doc Header" idlwave-doc-header t]
9103     ["Log" idlwave-doc-modification t]
9104     "--"
9105     ["Case" idlwave-case t]
9106     ["For" idlwave-for t]
9107     ["Repeat" idlwave-repeat t]
9108     ["While" idlwave-while t]
9109     "--"
9110     ["Close Block" idlwave-close-block t])
9111    ("Completion"
9112     ["Complete" idlwave-complete t]
9113     ("Complete Specific"
9114      ["1 Procedure Name" (idlwave-complete 'procedure) t]
9115      ["2 Procedure Keyword" (idlwave-complete 'procedure-keyword) t]
9116      "--"
9117      ["3 Function Name" (idlwave-complete 'function) t]
9118      ["4 Function Keyword" (idlwave-complete 'function-keyword) t]
9119      "--"
9120      ["5 Procedure Method Name" (idlwave-complete 'procedure-method) t]
9121      ["6 Procedure Method Keyword" (idlwave-complete 'procedure-method-keyword) t]
9122      "--"
9123      ["7 Function Method Name" (idlwave-complete 'function-method) t]
9124      ["8 Function Method Keyword" (idlwave-complete 'function-method-keyword) t]
9125      "--"
9126      ["9 Class Name"  idlwave-complete-class t]))
9127    ("Routine Info"
9128     ["Show Routine Info" idlwave-routine-info t]
9129     ["Online Context Help" idlwave-context-help t]
9130     "--"
9131     ["Find Routine Source" idlwave-find-module t]
9132     ["Resolve Routine" idlwave-resolve (featurep 'idlw-shell)]
9133     "--"
9134     ["Update Routine Info" idlwave-update-routine-info t]
9135     ["Rescan XML Help Catalog" idlwave-convert-xml-system-routine-info t]
9136     "--"
9137     "IDL User Catalog"
9138     ["Select Catalog Directories" (idlwave-create-user-catalog-file nil) t]
9139     ["Scan Directories" (idlwave-update-routine-info '(16))
9140      (and idlwave-path-alist (not idlwave-catalog-process))]
9141     ["Scan Directories &" (idlwave-update-routine-info '(64))
9142      (and idlwave-path-alist (not idlwave-catalog-process))]
9143     "--"
9144     "Routine Shadows"
9145     ["Check Current Buffer" idlwave-list-buffer-load-path-shadows t]
9146     ["Check Compiled Routines" idlwave-list-shell-load-path-shadows t]
9147     ["Check Everything" idlwave-list-all-load-path-shadows t])
9148    ("Misc"
9149     ["Kill auto-created buffers" idlwave-kill-autoloaded-buffers t]
9150     "--"
9151     ["Insert TAB character" idlwave-hard-tab t])
9152    "--"
9153    ("External"
9154     ["Start IDL shell" idlwave-shell t]
9155     ["Edit file in IDLDE" idlwave-edit-in-idlde t]
9156     ["Launch IDL Help" idlwave-launch-idlhelp t])
9157    "--"
9158    ("Customize"
9159     ["Browse IDLWAVE Group" idlwave-customize t]
9160     "--"
9161     ["Build Full Customize Menu" idlwave-create-customize-menu
9162      (fboundp 'customize-menu-create)])
9163    ("Documentation"
9164     ["Describe Mode" describe-mode t]
9165     ["Abbreviation List" idlwave-list-abbrevs t]
9166     "--"
9167     ["Commentary in idlwave.el" idlwave-show-commentary t]
9168     ["Commentary in idlw-shell.el" idlwave-shell-show-commentary t]
9169     "--"
9170     ["Info" idlwave-info t]
9171     "--"
9172     ["Help with Topic" idlwave-help-assistant-help-with-topic
9173      idlwave-help-use-assistant]
9174     ["Launch IDL Help" idlwave-launch-idlhelp t])))
9175
9176(defvar idlwave-mode-debug-menu-def
9177  '("Debug"
9178    ["Start IDL shell" idlwave-shell t]
9179    ["Save and .RUN buffer" idlwave-shell-save-and-run
9180     (and (boundp 'idlwave-shell-automatic-start)
9181	  idlwave-shell-automatic-start)]))
9182
9183(if (or (featurep 'easymenu) (load "easymenu" t))
9184    (progn
9185      (easy-menu-define idlwave-mode-menu idlwave-mode-map
9186			"IDL and WAVE CL editing menu"
9187			idlwave-mode-menu-def)
9188      (easy-menu-define idlwave-mode-debug-menu idlwave-mode-map
9189			"IDL and WAVE CL editing menu"
9190			idlwave-mode-debug-menu-def)))
9191
9192(defun idlwave-customize ()
9193  "Call the customize function with `idlwave' as argument."
9194  (interactive)
9195  ;; Try to load the code for the shell, so that we can customize it
9196  ;; as well.
9197  (or (featurep 'idlw-shell)
9198      (load "idlw-shell" t))
9199  (customize-browse 'idlwave))
9200
9201(defun idlwave-create-customize-menu ()
9202  "Create a full customization menu for IDLWAVE, insert it into the menu."
9203  (interactive)
9204  (if (fboundp 'customize-menu-create)
9205      (progn
9206	;; Try to load the code for the shell, so that we can customize it
9207	;; as well.
9208	(or (featurep 'idlw-shell)
9209	    (load "idlw-shell" t))
9210	(easy-menu-change
9211	 '("IDLWAVE") "Customize"
9212	 `(["Browse IDLWAVE group" idlwave-customize t]
9213	   "--"
9214	   ,(customize-menu-create 'idlwave)
9215	   ["Set" Custom-set t]
9216	   ["Save" Custom-save t]
9217	   ["Reset to Current" Custom-reset-current t]
9218	   ["Reset to Saved" Custom-reset-saved t]
9219	   ["Reset to Standard Settings" Custom-reset-standard t]))
9220	(message "\"IDLWAVE\"-menu now contains full customization menu"))
9221    (error "Cannot expand menu (outdated version of cus-edit.el)")))
9222
9223(defun idlwave-show-commentary ()
9224  "Use the finder to view the file documentation from `idlwave.el'."
9225  (interactive)
9226  (finder-commentary "idlwave.el"))
9227
9228(defun idlwave-shell-show-commentary ()
9229  "Use the finder to view the file documentation from `idlw-shell.el'."
9230  (interactive)
9231  (finder-commentary "idlw-shell.el"))
9232
9233(defun idlwave-info ()
9234  "Read documentation for IDLWAVE in the info system."
9235  (interactive)
9236  (info "idlwave"))
9237
9238(defun idlwave-list-abbrevs (arg)
9239  "Show the code abbreviations define in IDLWAVE mode.
9240This lists all abbrevs where the replacement text differs from the input text.
9241These are the ones the users want to learn to speed up their writing.
9242
9243The function does *not* list abbrevs which replace a word with itself
9244to call a hook.  These hooks are used to change the case of words or
9245to blink the matching `begin', and the user does not need to know them.
9246
9247With arg, list all abbrevs with the corresponding hook.
9248
9249This function was written since `list-abbrevs' looks terrible for IDLWAVE mode."
9250
9251  (interactive "P")
9252  (let ((table (symbol-value 'idlwave-mode-abbrev-table))
9253	abbrevs
9254	str rpl func fmt (len-str 0) (len-rpl 0))
9255    (mapatoms
9256     (lambda (sym)
9257       (if (symbol-value sym)
9258	   (progn
9259	     (setq str (symbol-name sym)
9260		   rpl (symbol-value sym)
9261		   func (symbol-function sym))
9262	     (if arg
9263		 (setq func (prin1-to-string func))
9264	       (if (and (listp func) (stringp (nth 2 func)))
9265		   (setq rpl (concat "EVAL: " (nth 2 func))
9266			 func "")
9267		 (setq func "")))
9268	     (if (or arg (not (string= rpl str)))
9269		 (progn
9270		   (setq len-str (max len-str (length str)))
9271		   (setq len-rpl (max len-rpl (length rpl)))
9272		   (setq abbrevs (cons (list str rpl func) abbrevs)))))))
9273     table)
9274    ;; sort the list
9275    (setq abbrevs (sort abbrevs (lambda (a b) (string< (car a) (car b)))))
9276    ;; Make the format
9277    (setq fmt (format "%%-%ds   %%-%ds   %%s\n" len-str len-rpl))
9278    (with-output-to-temp-buffer "*Help*"
9279      (if arg
9280	  (progn
9281	    (princ "Abbreviations and Actions in IDLWAVE-Mode\n")
9282	    (princ "=========================================\n\n")
9283	    (princ (format fmt "KEY" "REPLACE" "HOOK"))
9284	    (princ (format fmt "---" "-------" "----")))
9285	(princ "Code Abbreviations and Templates in IDLWAVE-Mode\n")
9286	(princ "================================================\n\n")
9287	(princ (format fmt "KEY" "ACTION" ""))
9288	(princ (format fmt "---" "------" "")))
9289      (dolist (list abbrevs)
9290	(setq str (car list)
9291	      rpl (nth 1 list)
9292	      func (nth 2 list))
9293	(princ (format fmt str rpl func)))))
9294  ;; Make sure each abbreviation uses only one display line
9295  (with-current-buffer "*Help*"
9296    (setq truncate-lines t)))
9297
9298(declare-function speedbar-add-supported-extension "speedbar" (extension))
9299
9300;; Add .pro files to speedbar for support, if it's loaded
9301(eval-after-load "speedbar" '(speedbar-add-supported-extension ".pro"))
9302
9303;; Set an idle timer to load the routine info.
9304;; Will only work on systems which support this.
9305(or idlwave-routines (idlwave-start-load-rinfo-timer))
9306
9307;; Run the hook
9308(run-hooks 'idlwave-load-hook)
9309
9310(provide 'idlwave)
9311
9312;;; idlwave.el ends here
9313