PageRenderTime 224ms CodeModel.GetById 209ms app.highlight 5ms RepoModel.GetById 1ms app.codeStats 1ms

/jEdit/tags/jedit-4-5-pre1/doc/users-guide/macro-tips.xml

#
XML | 921 lines | 729 code | 167 blank | 25 comment | 0 complexity | 2b539682b7accfb9b8bed917b8ae5271 MD5 | raw file
  1<?xml version="1.0" encoding="UTF-8"?>
  2<chapter id="macro-tips">
  3    <title>Macro Tips and Techniques</title>
  4
  5    <!-- jEdit 4.0 Macro Guide, (C) 2001, 2002 John Gellene       -->
  6
  7    <!-- Wed Jun 20 16:56:26 EDT 2001 @914 /Internet Time/        -->
  8
  9    <!--                                                          -->
 10
 11    <!-- jEdit buffer-local properties:                           -->
 12
 13    <!-- :indentSize=1:noTabs=yes:maxLineLen=0:wrap=soft:tabSize=2: -->
 14
 15    <!-- :xml.root=users-guide.xml:                               -->
 16
 17    <!--                                                          -->
 18
 19    <!-- This file covers the chapter "Macro tips and techniques" -->
 20
 21    <!-- $Id: macro-tips.xml 16181 2009-09-08 19:26:57Z ezust $
 22 -->
 23
 24    <section id="macro-tips-input">
 25        <title>Getting Input for a Macro</title>
 26
 27        <para>The dialog-based macro discussed in <xref
 28        linkend="dialog-macro" /> reflects a conventional approach to obtaining
 29        input in a Java program. Nevertheless, it can be too lengthy or tedious
 30        for someone trying to write a macro quickly. Not every macro needs a
 31        user interface specified in such detail; some macros require only a
 32        single keystroke or no input at all. In this section we outline some
 33        other techniques for obtaining input that will help you write macros
 34        quickly.</para>
 35
 36        <section id="macro-tips-input-single-line">
 37            <title>Getting a Single Line of Text</title>
 38
 39            <para>As mentioned earlier in <xref linkend="helpful-methods" />,
 40            the method <function>Macros.input()</function> offers a convenient
 41            way to obtain a single line of text input. Here is an example that
 42            inserts a pair of HTML markup tags specified by the user.</para>
 43
 44            <informalexample>
 45                <programlisting>// Insert_Tag.bsh
 46
 47void insertTag()
 48{
 49    caret = textArea.getCaretPosition();
 50    tag = Macros.input(view, <quote>Enter name of tag:</quote>);
 51    if( tag == null || tag.length() == 0) return;
 52    text = textArea.getSelectedText();
 53    if(text == null) text = <quote></quote>;
 54    sb = new StringBuffer();
 55    sb.append(<quote>&lt;</quote>).append(tag).append(<quote>&gt;</quote>);
 56    sb.append(text);
 57    sb.append(<quote>&lt;/</quote>).append(tag).append(<quote>&gt;</quote>);
 58    textArea.setSelectedText(sb.toString());
 59    if(text.length() == 0)
 60        textArea.setCaretPosition(caret + tag.length() + 2);
 61}
 62
 63insertTag();
 64
 65// end Insert_Tag.bsh</programlisting>
 66            </informalexample>
 67
 68            <para>Here the call to <function>Macros.input()</function> seeks the
 69            name of the markup tag. This method sets the message box title to a
 70            fixed string, <quote>Macro input</quote>, but the specific message
 71            <guilabel>Enter name of tag</guilabel> provides all the information
 72            necessary. The return value <varname>tag</varname> must be tested to
 73            see if it is null. This would occur if the user presses the
 74            <guilabel>Cancel</guilabel> button or closes the dialog window
 75            displayed by <function>Macros.input()</function>.</para>
 76        </section>
 77
 78        <section id="macro-tips-input-multiple-data">
 79            <title>Getting Multiple Data Items</title>
 80
 81            <para>If more than one item of input is needed, a succession of
 82            calls to <function>Macros.input()</function> is a possible, but
 83            awkward approach, because it would not be possible to correct early
 84            input after the corresponding message box is dismissed. Where more
 85            is required, but a full dialog layout is either unnecessary or too
 86            much work, the Java method
 87            <function>JOptionPane.showConfirmDialog()</function> is available.
 88            The version to use has the following prototype:</para>
 89
 90            <itemizedlist>
 91                <listitem>
 92                    <funcsynopsis>
 93                        <funcprototype>
 94                            <funcdef>public static int
 95                            <function>showConfirmDialog</function></funcdef>
 96
 97                            <paramdef>Component
 98                            <parameter>parentComponent</parameter></paramdef>
 99
100                            <paramdef>Object
101                            <parameter>message</parameter></paramdef>
102
103                            <paramdef>String
104                            <parameter>title</parameter></paramdef>
105
106                            <paramdef>int
107                            <parameter>optionType</parameter></paramdef>
108
109                            <paramdef>int
110                            <parameter>messageType</parameter></paramdef>
111                        </funcprototype>
112                    </funcsynopsis>
113                </listitem>
114            </itemizedlist>
115
116            <para>The usefulness of this method arises from the fact that the
117            <varname>message</varname> parameter can be an object of any Java
118            class (since all classes are derived from
119            <classname>Object</classname>), or any array of objects. The
120            following example shows how this feature can be used.</para>
121
122            <informalexample>
123                <programlisting>// excerpt from Write_File_Header.bsh
124
125title = <quote>Write file header</quote>;
126
127currentName = buffer.getName();
128
129nameField = new JTextField(currentName);
130authorField = new JTextField(<quote>Your name here</quote>);
131descField = new JTextField(<quote></quote>, 25);
132
133namePanel = new JPanel(new GridLayout(1, 2));
134nameLabel = new JLabel(<quote>Name of file:</quote>, SwingConstants.LEFT);
135saveField = new JCheckBox(<quote>Save file when done</quote>,
136    !buffer.isNewFile());
137namePanel.add(nameLabel);
138namePanel.add(saveField);
139
140
141message = new Object[9];
142message[0] = namePanel;
143message[1] = nameField;
144message[2] = Box.createVerticalStrut(10);
145message[3] = <quote>Author's name:</quote>;
146message[4] = authorField;
147message[5] = Box.createVerticalStrut(10);
148message[6] = <quote>Enter description:</quote>;
149message[7] = descField;
150message[8] = Box.createVerticalStrut(5);
151
152if( JOptionPane.OK_OPTION !=
153    JOptionPane.showConfirmDialog(view, message, title,
154        JOptionPane.OK_CANCEL_OPTION,
155        JOptionPane.QUESTION_MESSAGE))
156    return null;
157
158// *****remainder of macro script omitted*****
159
160// end excerpt from Write_File_Header.bsh</programlisting>
161            </informalexample>
162
163            <para>This macro takes several items of user input and produces a
164            formatted file header at the beginning of the buffer. The full macro
165            is included in the set of macros installed by jEdit. There are a
166            number of input features of this excerpt worth noting.</para>
167
168            <itemizedlist>
169                <listitem>
170                    <para>The macro uses a total of seven visible components.
171                    Two of them are created behind the scenes by
172                    <function>showConfirmDialog()</function>, the rest are made
173                    by the macro. To arrange them, the script creates an array
174                    of <classname>Object</classname> objects and assigns
175                    components to each location in the array. This translates to
176                    a fixed, top-to-bottom arrangement in the message box
177                    created by <function>showConfirmDialog()</function>.</para>
178                </listitem>
179
180                <listitem>
181                    <para>The macro uses <classname>JTextField</classname>
182                    objects to obtain most of the input data. The fields
183                    <varname>nameField</varname> and
184                    <varname>authorField</varname> are created with constructors
185                    that take the initial, default text to be displayed in the
186                    field as a parameter. When the message box is displayed, the
187                    default text will appear and can be altered or deleted by
188                    the user.</para>
189                </listitem>
190
191                <listitem>
192                    <para>The text field <varname>descField</varname> uses an
193                    empty string for its initial value. The second parameter in
194                    its constructor sets the width of the text field component,
195                    expressed as the number of characters of
196                    <quote>average</quote> width. When
197                    <function>showConfirmDialog()</function> prepares the layout
198                    of the message box, it sets the width wide enough to
199                    accommodate the designated with of
200                    <varname>descField</varname>. This technique produces a
201                    message box and input text fields that are wide enough for
202                    your data with one line of code.</para>
203                </listitem>
204
205                <listitem>
206                    <para>The displayed message box includes a
207                    <classname>JCheckBox</classname> component that determines
208                    whether the buffer will be saved to disk immediately after
209                    the file header is written. To conserve space in the message
210                    box, we want to display the check box to the right of the
211                    label <guilabel>Name of file:</guilabel>. To do that, we
212                    create a <classname>JPanel</classname> object and populate
213                    it with the label and the checkbox in a left-to-right
214                    <classname>GridLayout</classname>. The
215                    <classname>JPanel</classname> containing the two components
216                    is then added to the beginning of <varname>message</varname>
217                    array.</para>
218                </listitem>
219
220                <listitem>
221                    <para>The two visible components created by
222                    <function>showConfirmDialog()</function> appear at positions
223                    3 and 6 of the <varname>message</varname> array. Only the
224                    text is required; they are rendered as text labels.</para>
225                </listitem>
226
227                <listitem>
228                    <para>There are three invisible components created by
229                    <function>showConfirmDialog()</function>. Each of them
230                    involves a call to
231                    <function>Box.createVerticalStrut()</function>. The
232                    <classname>Box</classname> class is a sophisticated layout
233                    class that gives the user great flexibility in sizing and
234                    positioning components. Here we use a
235                    <function>static</function> method of the
236                    <classname>Box</classname> class that produces a vertical
237                    <glossterm>strut</glossterm>. This is a transparent
238                    component whose width expands to fill its parent component
239                    (in this case, the message box). The single parameter
240                    indicates the height of the strut in pixels. The last call
241                    to <function>createVerticalStrut()</function> separates the
242                    description text field from the <guilabel>OK</guilabel> and
243                    <guilabel>Cancel</guilabel> buttons that are automatically
244                    added by <function>showConfirmDialog()</function>.</para>
245                </listitem>
246
247                <listitem>
248                    <para>Finally, the call to
249                    <function>showConfirmDialog()</function> uses defined
250                    constants for the option type and the message type. The
251                    constants are the same as those used with the
252                    <function>Macros.confirm()</function> method; see <xref
253                    linkend="helpful-methods" />. The option type signifies the
254                    use of <guilabel>OK</guilabel> and
255                    <guilabel>Cancel</guilabel> buttons. The
256                    <constant>QUERY_MESSAGE</constant> message type causes the
257                    message box to display a question mark icon.</para>
258
259                    <para>The return value of the method is tested against the
260                    value <constant>OK_OPTION</constant>. If the return value is
261                    something else (because the <guilabel>Cancel</guilabel>
262                    button was pressed or because the message box window was
263                    closed without a button press), a <constant>null</constant>
264                    value is returned to a calling function, signaling that the
265                    user canceled macro execution. If the return value is
266                    <constant>OK_OPTION</constant>, each of the input components
267                    can yield their contents for further processing by calls to
268                    <function>JTextField.getText()</function> (or, in the case
269                    of the check box,
270                    <function>JCheckBox.isSelected()</function>).</para>
271                </listitem>
272            </itemizedlist>
273        </section>
274
275        <section id="tips-macro-input-combo">
276            <title>Selecting Input From a List</title>
277
278            <para>Another useful way to get user input for a macro is to use a
279            combo box containing a number of pre-set options. If this is the
280            only input required, one of the versions of
281            <function>showInputDialog()</function> in the
282            <classname>JOptionPane</classname> class provides a shortcut. Here
283            is its prototype:</para>
284
285            <itemizedlist>
286                <listitem>
287                    <funcsynopsis>
288                        <funcprototype>
289                            <funcdef>public static Object
290                            <function>showInputDialog</function></funcdef>
291
292                            <paramdef>Component
293                            <parameter>parentComponent</parameter></paramdef>
294
295                            <paramdef>Object
296                            <parameter>message</parameter></paramdef>
297
298                            <paramdef>String
299                            <parameter>title</parameter></paramdef>
300
301                            <paramdef>int
302                            <parameter>messageType</parameter></paramdef>
303
304                            <paramdef>Icon <parameter>icon</parameter></paramdef>
305
306                            <paramdef>Object[]
307                            <parameter>selectionValues</parameter></paramdef>
308
309                            <paramdef>Object
310                            <parameter>initialSelectionValue</parameter></paramdef>
311                        </funcprototype>
312                    </funcsynopsis>
313                </listitem>
314            </itemizedlist>
315
316            <para>This method creates a message box containing a drop-down list
317            of the options specified in the method's parameters, along with
318            <guilabel>OK</guilabel> and <guilabel>Cancel</guilabel> buttons.
319            Compared to <function>showConfirmDialog()</function>, this method
320            lacks an <varname>optionType</varname> parameter and has three
321            additional parameters: an <varname>icon</varname> to display in the
322            dialog (which can be set to <constant>null</constant>), an array of
323            <varname>selectionValues</varname> objects, and a reference to one
324            of the options as the <varname>initialSelectionValue</varname> to be
325            displayed. In addition, instead of returning an
326            <classname>int</classname> representing the user's action,
327            <function>showInputDialog()</function> returns the
328            <classname>Object</classname> corresponding to the user's selection,
329            or <constant>null</constant> if the selection is canceled.</para>
330
331            <para>The following macro fragment illustrates the use of this
332            method.</para>
333
334            <informalexample>
335                <programlisting>// fragment illustrating use of showInputDialog()
336options = new Object[5];
337options[0] = "JLabel";
338options[1] = "JTextField";
339options[2] = "JCheckBox";
340options[3] = "HistoryTextField";
341options[4} = "-- other --";
342
343result = JOptionPane.showInputDialog(view,
344    "Choose component class",
345    "Select class for input component",
346    JOptionPane.QUESTION_MESSAGE,
347    null, options, options[0]);</programlisting>
348            </informalexample>
349
350            <para>The return value <varname>result</varname> will contain either
351            the <classname>String</classname> object representing the selected
352            text item or <constant>null</constant> representing no selection.
353            Any further use of this fragment would have to test the value of
354            <varname>result</varname> and likely exit from the macro if the
355            value equaled <constant>null</constant>.</para>
356
357            <para>A set of options can be similarly placed in a
358            <classname>JComboBox</classname> component created as part of a
359            larger dialog or <function>showMessageDialog()</function> layout.
360            Here are some code fragments showing this approach:</para>
361
362            <informalexample>
363                <programlisting>// fragments from Display_Abbreviations.bsh
364// import statements and other code omitted
365
366// from main routine, this method call returns an array
367// of Strings representing the names of abbreviation sets
368
369abbrevSets = getActiveSets();
370
371...
372
373// from showAbbrevs() method
374
375combo = new JComboBox(abbrevSets);
376// set width to uniform size regardless of combobox contents
377Dimension dim = combo.getPreferredSize();
378dim.width = Math.max(dim.width, 120);
379combo.setPreferredSize(dim);
380combo.setSelectedItem(STARTING_SET); // defined as "global"
381
382// end fragments</programlisting>
383            </informalexample>
384        </section>
385
386        <section id="macro-tips-single-char">
387            <title>Using a Single Keypress as Input</title>
388
389            <para>Some macros may choose to emulate the style of character-based
390            text editors such as <application>emacs</application> or
391            <application>vi</application>. They will require only a single
392            keypress as input that would be handled by the macro but not
393            displayed on the screen. If the keypress corresponds to a character
394            value, jEdit can pass that value as a parameter to a BeanShell
395            script.</para>
396
397            <para>The jEdit class <ulink
398            url="../api/org/gjt/sp/jedit/gui/InputHandler.html">InputHandler</ulink>
399            is an abstract class that that manages associations between keyboard
400            input and editing actions, along with the recording of macros.
401            Keyboard input in jEdit is normally managed by the derived class
402            <ulink
403            url="../api/org/gjt/sp/jedit/gui/DefaultInputHandler.html">DefaultInputHandler</ulink>.
404            One of the methods in the <ulink
405            url="../api/org/gjt/sp/jedit/gui/InputHandler.html">InputHandler</ulink>
406            class handles input from a single keypress:</para>
407
408            <itemizedlist>
409                <listitem>
410                    <funcsynopsis>
411                        <funcprototype>
412                            <funcdef>public void
413                            <function>readNextChar</function></funcdef>
414
415                            <paramdef>String
416                            <parameter>prompt</parameter></paramdef>
417
418                            <paramdef>String
419                            <parameter>code</parameter></paramdef>
420                        </funcprototype>
421                    </funcsynopsis>
422                </listitem>
423            </itemizedlist>
424
425            <para>When this method is called, the contents of the
426            <varname>prompt</varname> parameter is shown in the view's status
427            bar. The method then waits for a key press, after which the contents
428            of the <varname>code</varname> parameter will be run as a BeanShell
429            script, with one important modification. Each time the string
430            <varname>__char__</varname> appears in the parameter script, it will
431            be substituted by the character pressed. The key press is
432            <quote>consumed</quote> by <function>readNextChar()</function>. It
433            will not be displayed on the screen or otherwise processed by
434            jEdit.</para>
435
436            <para>Using <function>readNextChar()</function> requires a macro
437            within the macro, formatted as a single, potentially lengthy string
438            literal. The following macro illustrates this technique. It selects
439            a line of text from the current caret position to the first
440            occurrence of the character next typed by the user. If the character
441            does not appear on the line, no new selection occurs and the display
442            remains unchanged.</para>
443
444            <informalexample>
445                <programlisting>// Next_Char.bsh
446
447script = new StringBuffer(512);
448script.append( "start = textArea.getCaretPosition();"         );
449script.append( "line = textArea.getCaretLine();"              );
450script.append( "end = textArea.getLineEndOffset(line) + 1;"   );
451script.append( "text = buffer.getText(start, end - start);"   );
452script.append( "match = text.indexOf(__char__, 1);"           );
453script.append( "if(match != -1) {"                            );
454script.append(   "if(__char__ != '\\n') ++match;"             );
455script.append(   "textArea.select(start, start + match - 1);" );
456script.append( "}"                                            );
457
458view.getInputHandler().readNextChar("Enter a character",
459    script.toString());
460
461// end Next_Char.bsh</programlisting>
462            </informalexample>
463
464            <para>Once again, here are a few comments on the macro's
465            design.</para>
466
467            <itemizedlist>
468                <listitem>
469                    <para>A <classname>StringBuffer</classname> object is used
470                    for efficiency; it obviates multiple creation of
471                    fixed-length <classname>String</classname> objects. The
472                    parameter to the constructor of <varname>script</varname>
473                    specifies the initial size of the buffer that will receive
474                    the contents of the child script.</para>
475                </listitem>
476
477                <listitem>
478                    <para>Besides the quoting of the script code, the formatting
479                    of the macro is entirely optional but (hopefully) makes it
480                    easier to read.</para>
481                </listitem>
482
483                <listitem>
484                    <para>It is important that the child script be
485                    self-contained. It does not run in the same namespace as the
486                    <quote>parent</quote> macro
487                    <filename>Next_Char.bsh</filename> and therefore does not
488                    share variables, methods, or scripted objects defined in the
489                    parent macro.</para>
490                </listitem>
491
492                <listitem>
493                    <para>Finally, access to the <ulink
494                    url="../api/org/gjt/sp/jedit/gui/InputHandler.html">InputHandler</ulink>
495                    object used by jEdit is available by calling
496                    <function>getInputHandler()</function> on the current
497                    view.</para>
498                </listitem>
499            </itemizedlist>
500        </section>
501    </section>
502
503    <section id="startup-scripts">
504        <title>Startup Scripts</title>
505
506        <para>On startup, jEdit runs any BeanShell scripts located in the
507        <filename>startup</filename> subdirectory of the jEdit installation and
508        user settings directories (see <xref linkend="settings-directory" />).
509        As with macros, the scripts must have a <filename>.bsh</filename> file
510        name extension. Startup scripts are run near the end of the startup
511        sequence, after plugins, properties and such have been initialized, but
512        before the first view is opened.</para>
513
514        <para>Startup scripts can perform initialization tasks that cannot be
515        handled by command line options or ordinary configuration options, such
516        as customizing jEdit's user interface by changing entries in the Java
517        platform's <classname>UIManager</classname> class.</para>
518
519        <para>Startup scripts have an additional feature lacking in ordinary
520        macros that can help you further customize jEdit. Variables and methods
521        defined in a startup script are available in all instances of the
522        BeanShell interpreter created in jEdit. This allows you to create a
523        personal library of methods and objects that can be accessed at any time
524        during the editing session in another macro, the BeanShell shell of the
525        Console plugin, or menu items such as
526        <guimenu>Utilities</guimenu>&gt;<guisubmenu>BeanShell</guisubmenu>&gt;<guimenuitem>Evaluate
527        BeanShell Expression</guimenuitem>.</para>
528
529        <para>The startup script routine will run script files in the
530        installation directory first, followed by scripts in the user settings
531        directory. In each case, scripts will be executed in alphabetical order,
532        applied without regard to whether the file name contains upper or lower
533        case characters.</para>
534
535        <para>If a startup script throws an exception (because, for example, it
536        attempts to call a method on a <constant>null</constant> object). jEdit
537        will show an error dialog box and move on to the next startup script. If
538        script bugs are causing jEdit to crash or hang on startup, you can use
539        the <userinput>-nostartupscripts</userinput> command line option to
540        disable them for that editing session.</para>
541
542        <para>Another important difference between startup scripts and ordinary
543        macros is that startup scripts cannot use the pre-defined variables
544        <varname>view</varname>, <varname>textArea</varname>,
545        <varname>editPane</varname> and <varname>buffer</varname>. This is
546        because they are executed before the initial view is created.</para>
547
548        <para>If you are writing a method in a startup script and wish to use
549        one of the above variables, pass parameters of the appropriate type to
550        the method, so that a macro calling them after startup can supply the
551        appropriate values. For example, a startup script could include a
552        method</para>
553
554        <informalexample>
555            <programlisting>void doSomethingWithView(View v, String s)  {
556    ...
557}</programlisting>
558        </informalexample>
559
560        <para>so that during the editing session another macro can call the
561        method using</para>
562
563        <informalexample>
564            <programlisting>doSomethingWithView(view, "something");</programlisting>
565        </informalexample>
566
567        <sidebar>
568            <title>Reloading startup scripts without restarting</title>
569
570            <para>It is actually possible to reload startup scripts or load
571            other scripts without restarting jEdit, using a BeanShell statement
572            like the following:</para>
573
574            <programlisting>BeanShell.runScript(view,<replaceable>path</replaceable>,null,false);</programlisting>
575
576            <para>For <replaceable>path</replaceable>, you can substitute any
577            string, or a method call such as
578            <function>buffer.getPath()</function>.</para>
579        </sidebar>
580    </section>
581
582    <section id="scripts-command-line">
583        <title>Running Scripts from the Command Line</title>
584
585        <para>The <userinput>-run</userinput> command line switch specifies a
586        BeanShell script to run on startup:</para>
587
588        <screen><prompt>$ </prompt><userinput>jedit -run=test.bsh</userinput></screen>
589
590        <para>Note that just like with startup scripts, the
591        <varname>view</varname>, <varname>textArea</varname>,
592        <varname>editPane</varname> and <varname>buffer</varname> variables are
593        not defined.</para>
594
595        <para>If another instance is already running, the script will be run in
596        that instance, and you will be able to use the
597        <function>jEdit.getLastView()</function> method to obtain a view.
598        However, if a new instance of jEdit is being started, the script will be
599        run at the same time as all other startup scripts; that is, before the
600        first view is opened.</para>
601
602        <para>If your script needs a view instance to operate on, you can use
603        the following code pattern to obtain one, no matter how or when the
604        script is being run:</para>
605
606        <programlisting>void doSomethingUseful()
607{
608    void run()
609    {
610        view = jEdit.getLastView();
611
612        // put actual script body here
613    }
614
615    if(jEdit.getLastView() == null)
616        VFSManager.runInAWTThread(this);
617    else
618        run();
619}
620
621doSomethingUseful();</programlisting>
622
623        <para>If the script is being run in a loaded instance, it can be invoked
624        to perform its work immediately. However, if the script is running at
625        startup, before an initial view exists, its operation must be delayed to
626        allow the view object first to be created and displayed. In order to
627        queue the macro's operation, the scripted <quote>closure</quote> named
628        <function>doSomethingUseful()</function> implements the
629        <classname>Runnable</classname> interface of the Java platform. That
630        interface contains only a single <function>run()</function> method that
631        takes no parameters and has no return value. The macro's implementation
632        of the <function>run()</function> method contains the
633        <quote>working</quote> portion of the macro. Then the scripted object,
634        represented by a reference to <varname>this</varname>, is passed to the
635        <function>runInAWTThread()</function> method. This schedules the macro's
636        operations for execution after the startup routine is complete.</para>
637
638        <para>As this example illustrates, the
639        <function>runInAWTThread()</function> method can be used to ensure that
640        a macro will perform operations after other operations have completed.
641        If it is invoked during startup, it schedules the specified
642        <classname>Runnable</classname> object to run after startup is complete.
643        If invoked when jEdit is fully loaded, the
644        <classname>Runnable</classname> object will execute after all pending
645        input/output is complete, or immediately if there are no pending I/O
646        operations. This will delay operations on a new buffer, for example,
647        until after the buffer is loaded and displayed.</para>
648    </section>
649
650    <section id="macro-tips-BeanShell">
651        <title>Advanced BeanShell Techniques</title>
652
653        <para>BeanShell has a few advanced features that we haven't mentioned
654        yet. They will be discussed in this section.</para>
655
656        <section id="macro-tips-BeanShell-convenience">
657            <title>BeanShell's Convenience Syntax</title>
658
659            <para>We noted earlier that BeanShell syntax does not require that
660            variables be declared or defined with their type, and that variables
661            that are not typed when first used can have values of differing
662            types assigned to them. In addition to this <quote>loose</quote>
663            syntax, BeanShell allows a <quote>convenience</quote> syntax for
664            dealing with the properties of JavaBeans. They may be accessed or
665            set as if they were data members. They may also be accessed using
666            the name of the property enclosed in quotation marks and curly
667            brackets. For example, the following statement are all equivalent,
668            assuming <varname>btn</varname> is a <classname>JButton</classname>
669            instance:</para>
670
671            <informalexample>
672                <programlisting>b.setText("Choose");
673b.text = "Choose";
674b{"text"} = "Choose";
675</programlisting>
676            </informalexample>
677
678            <para>The last form can also be used to access a key-value pair of a
679            <classname>Hashtable</classname> object.</para>
680
681            <!-- actually, the following requires the bsh.classpath package, which
682     is not included with jEdit at this point in time.
683
684     a future release of jEdit will use bsh.classpath, and hence support
685     'import *'
686
687<para>
688  Finally, when importing classes, BeanShell permits the following form
689  to import all classes lying within the interpreter's classpath:
690</para>
691
692<informalexample><programlisting>import *;
693</programlisting></informalexample>
694
695-->
696        </section>
697
698        <section id="macro-tips-BeanShell-keywords">
699            <title>Special BeanShell Keywords</title>
700
701            <para>BeanShell uses special keywords to refer to variables or
702            methods defined in the current or an enclosing block's scope:</para>
703
704            <itemizedlist>
705                <listitem>
706                    <para>The keyword <function>this</function> refers to the
707                    current scope.</para>
708                </listitem>
709
710                <listitem>
711                    <para>The keyword <function>super</function> refers to the
712                    immediately enclosing scope.</para>
713                </listitem>
714
715                <listitem>
716                    <para>The keyword <function>global</function> refers to the
717                    top-level scope of the macro script.</para>
718                </listitem>
719            </itemizedlist>
720
721            <para>The following script illustrates the use of these
722            keywords:</para>
723
724            <informalexample>
725                <programlisting>a = "top\n";
726foo() {
727    a = "middle\n";
728    bar() {
729        a = "bottom\n";
730        textArea.setSelectedText(global.a);
731        textArea.setSelectedText(super.a);
732        // equivalent to textArea.setSelectedText(this.a):
733        textArea.setSelectedText(a);
734    }
735
736    bar();
737}
738foo();</programlisting>
739            </informalexample>
740
741            <para>When the script is run, the following text is inserted in the
742            current buffer:</para>
743
744            <screen>top
745middle
746bottom</screen>
747        </section>
748
749        <section id="macro-tips-BeanShell-class">
750            <title>Implementing Classes and Interfaces</title>
751
752            <para>As discussed in the macro example in <xref
753            linkend="dialog-macro" />, scripted objects can implicitly implement
754            Java interfaces such as <classname>ActionListener</classname>. For
755            example:</para>
756
757            <programlisting>myRunnable() {
758    run() {
759        System.out.println("Hello world!");
760    }
761
762    return this;
763}
764
765Runnable r = myRunnable();
766new Thread(r).start();</programlisting>
767
768            <para>Frequently it will not be necessary to implement all of the
769            methods of a particular interface in order to specify the behavior
770            of a scripted object. To prevent BeanShell from throwing exceptions
771            for missing interface methods, implement the
772            <function>invoke()</function> method, which is called when an
773            undefined method is invoked on a scripted object. Typically, the
774            implementation of this method will do nothing, as in the following
775            example:</para>
776
777            <informalexample>
778                <programlisting>invoke(method, args) {}</programlisting>
779            </informalexample>
780
781            <para>In addition to the implicit interface definitions described
782            above, BeanShell permits full-blown classes to be defined. Indeed,
783            almost any Java class definition should work in BeanShell:</para>
784
785            <programlisting>class Cons {
786    // Long-live LISP!
787    Object car;
788    Object cdr;
789
790    rplaca(Object car) {
791        this.car = car;
792    }
793
794    rplacd(Object cdr) {
795        this.cdr = cdr;
796    }
797}</programlisting>
798        </section>
799    </section>
800
801    <section id="macro-tips-debugging">
802        <title>Debugging Macros</title>
803
804        <para>Here are a few techniques that can prove helpful in debugging
805        macros.</para>
806
807        <section id="macro-tips-debugging-exceptions">
808            <title>Identifying Exceptions</title>
809
810            <para>An <glossterm>exception</glossterm> is a condition reflecting
811            an error or other unusual result of program execution that requires
812            interruption of normal program flow and some kind of special
813            handling. Java has a rich (and extensible) collection of exception
814            classes which represent such conditions.</para>
815
816            <para>jEdit catches exceptions thrown by BeanShell scripts and
817            displays them in a dialog box. In addition, the full traceback is
818            written to the activity log (see <xref linkend="activity-log" /> for
819            more information about the activity log).</para>
820
821            <para>There are two broad categories of errors that will result in
822            exceptions:</para>
823
824            <itemizedlist>
825                <listitem>
826                    <para><emphasis>Interpreter errors</emphasis>, which may
827                    arise from typing mistakes like mismatched brackets or
828                    missing semicolons, or from BeanShell's failure to find a
829                    class corresponding to a particular variable.</para>
830
831                    <para>Interpreter errors are usually accompanied by the line
832                    number in the script, along with the cause of the
833                    error.</para>
834                </listitem>
835
836                <listitem>
837                    <para><emphasis>Execution errors</emphasis>, which result
838                    from runtime exceptions thrown by the Java platform when
839                    macro code is executed.</para>
840
841                    <para>Some exceptions thrown by the Java platform can often
842                    seem cryptic. Nevertheless, examining the contents of the
843                    activity log may reveals clues as to the cause of the
844                    error.</para>
845                </listitem>
846            </itemizedlist>
847        </section>
848
849        <section id="macro-tips-debugging-log">
850            <title>Using the Activity Log as a Tracing Tool</title>
851
852            <para>Sometimes exception tracebacks will say what kind of error
853            occurred but not where it arose in the script. In those cases, you
854            can insert calls that log messages to the activity log in your
855            macro. If the logged messages appear when the macro is run, it means
856            that up to that point the macro is fine; but if an exception is
857            logged first, it means the logging call is located after the cause
858            of the error.</para>
859
860            <para>To write a message to the activity log, use the following
861            method of the <ulink
862            url="../api/org/gjt/sp/util/Log.html">Log</ulink> class:</para>
863
864            <itemizedlist>
865                <listitem>
866                    <funcsynopsis>
867                        <funcprototype>
868                            <funcdef>public static void
869                            <function>log</function></funcdef>
870
871                            <paramdef>int
872                            <parameter>urgency</parameter></paramdef>
873
874                            <paramdef>Object
875                            <parameter>source</parameter></paramdef>
876
877                            <paramdef>Object
878                            <parameter>message</parameter></paramdef>
879                        </funcprototype>
880                    </funcsynopsis>
881                </listitem>
882            </itemizedlist>
883
884            <para>See the documentation for the <ulink
885            url="../api/org/gjt/sp/util/Log.html">Log</ulink> class for
886            information about the method's parameters.</para>
887
888            <para>The following code sends a typical debugging message to the
889            activity log:</para>
890
891            <informalexample>
892                <programlisting>Log.log(Log.DEBUG, BeanShell.class,
893    "counter = " + counter);</programlisting>
894            </informalexample>
895
896            <para>The corresponding activity log entry might read as
897            follows:</para>
898
899            <informalexample>
900                <programlisting>[debug] BeanShell: counter = 15</programlisting>
901            </informalexample>
902
903            <sidebar>
904                <title>Using message dialog boxes as a tracing tool</title>
905
906                <para>If you would prefer not having to deal with the activity
907                log, you can use the <function>Macros.message()</function>
908                method as a tracing tool. Just insert calls like the following
909                in the macro code:</para>
910
911                <programlisting>Macros.message(view,"tracing");</programlisting>
912
913                <para>Execution of the macro is halted until the message dialog
914                box is closed. When you have finished debugging the macro, you
915                should delete or comment out the debugging calls to
916                <function>Macros.message()</function> in your final source
917                code.</para>
918            </sidebar>
919        </section>
920    </section>
921</chapter>